text
stringlengths
37
1.41M
class Stopwords: words = ['a', 'about', 'all', 'an', 'and', 'any', 'are', 'as', \ 'at', 'be', 'been', 'but', 'by', 'can', 'could', 'do', \ 'does', 'for', 'from', 'has', 'have', 'he', 'her', 'his', \ 'how', 'i', 'if', 'in', 'into', 'is', 'it', 'its', 'made', \ 'make'...
import turtle window = turtle.Screen() window.bgcolor("white") pen = turtle.Turtle() pen.speed(1) pen.shape("turtle") pen.color("black") pen.goto(-100, -75) pen.right(90) count = 0 while count < 4: pen.forward(200) pen.right(90) count += 1 pen.left(90) pen.forward(300) while count < 6: pen.left(90) ...
def push_up_total(pushups, days, day_num=1): if days < day_num: return else: print("\n\nday = "+ str(day_num)) print("push ups " + str(pushups)) push_up_total(pushups*2,days, day_num+1) starting_num = int(input("how many push ups will you start with? ")) num_of_days = int(input(...
#To Translate a DNA Sequence from a File in FASTA Format and Also to Generate the Exons from that Protein Sequence: import sys import re from itertools import takewhile # (1) To Generate a Protein Sequence from a DNA Sequence: def translate(filename): #To Create a Dictionary of all the codons and their correspond...
c = int(input()) r = int(input()) k = int(input()) zoom = dict() # a example of a word for s in range(k): ch = str(input()) # create the example by a 2d array zoomIn = [[0 for i in range(c)] for j in range(r)] for i in range(r): row = list(str(input())) #for j in range(c): ...
import math # Python3 program to find (a^b) % MOD # where a and b may be very large # and represented as strings. MOD = 1000000007 # https://www.geeksforgeeks.org/modulo-power-for-large-numbers-represented-as-strings/ # Returns modulo exponentiation # for two numbers represented as # long long int. It is ...
#!/bin/python # Head ends here def insertionSort(m,ar): if m < 2: print(' '.join([str(x) for x in ar])) for index in range(1,m): while ar[index] < ar[index-1]: ar[index], ar[index-1] = ar[index-1],ar[index] if index > 1: index -= 1 print(' ...
l = int(input()) ar = input().split() for size in range(l): ar[size] = int(ar[size]) def shift(plist, index): temp = plist[index] if plist[index-1] > plist[index]: plist[index] = plist[index-1] plist[index-1] = temp if index - 2 == -1: pass else: ...
""" File with classes and special functions that are required at some point in the project """ from datetime import datetime import pandas as pd import shutil import os import zipfile import openpyxl class Message: """ A class used to represent the message that is exchanged between server and clients. This m...
""" Main Script of the project. It initiates the server and set it to listen for connections of clients. The server keeps listening until the maximum number of connected clients is reached. """ from Modules.Config.Connection import Connection from Modules.Config.Data import verify_ip, verify_port import os import shuti...
#!/usr/bin/env python3 """ Created by tao.liu on 2018/7/31. 迭代器和生成器 """ import sys list = [1, 2, 3, 4] it = iter(list) # 创建迭代器对象 for x in it: print(x, end=" ") list = [1, 2, 3, 4, 5] it = iter(list) # 创建迭代器对象 while True: try: print(next(it)) except StopIteration: sys.exit()
import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model # X is a 10x10 matrix X = 1. / (np.arange(1, 11) + np.arange(0, 10)[:, np.newaxis]) # y is a 10 x 1 vector y = np.ones(10) n_alphas = 200 # alphas count is 200, 都在10的-10次方和10的-2次方之间 alphas = np.logspace(-10, -2, n_alphas) ...
from typing import Union from collections import namedtuple import pprint class SymbolTable: def __init__(self): """ Creates a new empty symbol table. """ self.table = dict() self.identifier = namedtuple("Identifier", ["name", "type", "kind", "index"]) def start_su...
# makes moves and learns new states using Q-learning # 3-3-2020 __author__ = '20wang' # much assistance from here: https://towardsdatascience.com/q-learning-54b841f3f9e4 from random import randint class Thinker(object): # class constructor def __init__(self, rando, rate): self.moves = [] se...
"""Customers at Hackbright.""" class Customer(object): """Ubermelon customer.""" # TODO: need to implement this def __init__(self, first_name, last_name, email, password): """Initialize a customer class.""" self.first_name = first_name self.last_name = last_name self.ema...
def get_answer(question): answers={'привет':'И тебе привет','как дела?':'лучше всех!','пока':'увидимся'} if question not in answers: print('Спроси что-то другое') else: return answers[question] question=input().lower() print(get_answer(question))
# -*- coding: utf-8 -*- """ Exercise 10: attributes: int (maxi): the maximum number of elements accepted in the stack list (content): to store the items pushed in the stack methods: __init__ push __str__ __len__ pop peek __eq__ (optional) """ cl...
from BeautifulSoup import BeautifulSoup import requests import urllib2 import re #importing requirements html_page = urllib2.urlopen("https://unsplash.com/") #opening the webpage soup = BeautifulSoup(html_page) #instance of the BeautifulSoup class images = [] #declaring the list for img in soup.findAll('img'): ...
# space.py import turtle import math import random import os # Move player to the right def move_right(): x = player.xcor() x = x + playerspeed if x > 280: x = 280 player.setx(x) def move_left(): x = player.xcor() x = x - playerspeed if x < -280: x = -280 player.setx(x) def fire_bullet(): # Declare bul...
import time from os import system, name import numpy as np class Player: marker = "" def __init__(self,marker): self.marker = marker def get_player_marker(self): return self.marker def get_player_move(self): move = np.empty(2) print("Press enter once you finish...
# idade_str = input("Digite sua idade: ") # idade = int(idade_str) # if (idade > 18): # print("Você é maior de idade.") # else: # if (idade < 12): # print("Você é uma criança.") # elif (idade > 12): # print("Você é um adolescente.") # idade_str = input("Digite sua idade: ") # idade = int(i...
number = 1 if number > 1: for i in range(2, number): if (number % i) == 0: print(False) break else: print(True) else: print(False)
def main(): print("Please enter the phrase to be encrypted or decrypted: ") phrase = list(input()) print("Please enter the key:") key = validKey(input()) print("Are we Encrypting (1) or Decrypting (2)?") choice = input() if(choice == '1'): encrypt(phrase, key) pass if(choice == '2'): decrypt(phrase, k...
from typing import List class Square: def __init__(self, value='#'): self._value = value @property def value(self): return self._value @value.setter def value(self, value): print(f"Setting the value ...") if value == None: raise Exception("value must ...
""" This program takes two numbers as user input and compares them to see if 'a' is less than, more than or equal to 'b' """ # Compare function compares two number and returns result. def compare(a, b): if a < b: return -1 elif a == b: return 0 elif a > b: return 1 # Compare test v...
from assignworkers import assignWorkers from fileRead import fileRead import prettyprint #File Read to compute the days off for people off_days = fileRead() #Logic of assignments assign = assignWorkers(off_days) #Assigned days and names - Global Variables assigned_days = assign[0] assigned_names = assign[1] #Menu ...
i=0 numbers=[] def numberfind(i,q): while i < q: print(f"At the top i is {i}") numbers.append(i) print("What should I add to the number?") in_num = input("->") i = i + int(in_num) print("Numbers now:", numbers) print(f"At the botom i is {i}") numberfind(2,7)...
animals = ['bear', 'python', 'peacock','kangaroo','whale','platypus'] print(" The animal at 1 is a", animals[0]) print(" The third animal is a", animals[2]) print (" The first animal is a ", animals[0]) print (" The animal at 2 is a", animals[1]) print (" The animal at 4 is a ", animals[3])
print("\n\n") def is_prime(x): counter = 0 numbers = [2,3,4,5,6,7,8,9] for b in range(len(numbers)): if x % numbers[b] == 0: counter += 1 if x == 1: counter += 1 if x == numbers[b]: counter -= 1 if counter == 0 : return True return ...
import math def safe_sqrt(x): try: x = int(x) try: x > -1 return int(math.sqrt(x)) except: return 1 except: return 0 assert safe_sqrt(-1) == 1, "-1 should lead to 1" assert safe_sqrt('a') == 0, "Character should lead to 0" assert safe_sqrt(...
people = 20 cats = 30 dogs = 45 if people < cats: #if True do the following: print("Too many cats! The world is doomed") #needs for inspaces or tab so it is asigned to the last question. if people > cats: print("Not many cats! The world is saved") if people < dogs: print("The world is drooled on") if p...
sent = "yeah dude!" def border_around_text(sentence,symbol = '+',padding = 1): #SETUP# words = sentence.split(" ") longest_word = '' for i in words: if len(i)>len(longest_word): longest_word=i len_long_word = len(longest_word) total_space = 2+(2*padding)+len(longest_word) ...
import speech_recognition as sr import tkinter import tkinter.filedialog root = tkinter.Tk() def openfile(): global f f = tkinter.filedialog.askopenfilename( parent=root, title='Choose file', filetypes=[('Audio Files', '*.wav'), ("All Files", "*.*")] ) ...
import Tkinter def get(): print E1.get() text_area.insert(Tkinter.INSERT, E1.get()) text_area.insert(Tkinter.INSERT, "\n\n\n") top = Tkinter.Tk() text_area = Tkinter.Text() text_area.pack(side = Tkinter.TOP) L1 = Tkinter.Label(top, text="Enter handle") L1.pack( side = Tkinter.LEFT) E1 = Tkinter....
''' Submitted By:Sadia khanam 5th Batch Department of Computer Science & Engineering University Of Barisal ''' X = list(map(int, input("Enter the unsorted array:").split())) # X=[0 5 8 9 4 2 5 21 11] def InsertionSort(X): for j in range(1, len(X)): key = X[j]; i = j - 1 while (i ...
#!/usr/bin/env python3 import sys input_lines = [] for line in sys.stdin: input_lines.append(line) connections = [] for i in range(2,len(input_lines)): connection = input_lines[i].replace("\r","").replace("\n","") connections.append(connection) simpleConnections = [] redundantConnections = [] for connecti...
from question import Question from utils import randomize, verify_option class Bank: # Class Constructor. def __init__(self): self.categories = ["Entretenimiento", "Geografía", "Historia", "Ciencia", "Deportes"] self.rank1 = { 0: Question(self.categories[...
""" @author: Anirudh Sharma """ def efficient_fibonacci(n, d): if n in d: return d[n] else: result = efficient_fibonacci(n - 1, d) + efficient_fibonacci(n - 2, d) d[n] = result return result d = {1:1, 2:2} print(efficient_fibonacci(34, d))
""" @author: Anirudh Sharma You have graduated from MIT and now have a great job! You move to the San Francisco Bay Area and decide that you want to start saving to buy a house. As housing prices are very high in the Bay Area, you realize you are going to have to save for several years before you can afford to make t...
#!/usr/bin/env python # Cubifies words. Currently only works with strings of even length. # Todo: turn this into an aws(or other service) api? usr_str = raw_input("Enter string to be cubified: ") print if len(usr_str) % 2 != 0: print "Sorry, this only works with strings of even length." ...
#!/usr/bin/env python # [2015-06-08] Challenge #218 [Easy] Making numbers palindromic # http://bit.ly/1C4nMf9 from collections import defaultdict def reverse_digits(x): return int(str(x)[::-1]) def is_palindrome(s): if type(s) != str: s = str(s) return s == s[::-1] def calc(origin): val = o...
# x = "* * * *" # y = " * * * *" # l = 1 # while l <= 4: # print x # print y # l +=1 # for x in range(1,6): # print (5-x)*' ' + " ".join(['*']*x) # def pattern(n): # for x in range( 1, n+1 ): # print (n-x)*' ' + " ".join(['*']*x) # pattern(30) def multiply(arr,num): for x in range(...
# class and Object Problem ''' Problem 1 : Define a class Student with instance variables rollno, name, semester, branch. Also define instance member function for user input data to set values of instance variables and Display student data ''' class Student: def __init__(self,rollno,name,semeste...
from math import sqrt from random import randint class Rocket: def __init__(self, speed=1, altitude=0, x=0): self.altitude = altitude self.x = x self.speed = speed def moveUp(self): self.altitude += self.speed def __str__(self): return "Rakieta jest aktualnie na ...
#!/usr/bin/python3 """ FileStorage class """ import json from os import path from models.base_model import BaseModel from models.user import User from models.state import State from models.city import City from models.amenity import Amenity from models.place import Place from models.review import Review class FileSto...
#conragulating the user for completing the quiz and thanking them print("\nYou have succesfully completed Hafidz's Game Quiz!") #displaying the score and percentage (performance) print("Conragulations! "+name,", your final score is", score,"out of",total) print("That means you answered", (round(score/total*100,2)),...
#the variable will be called name #ask for user input name = input("Please Enter Your Name : ") #print name print("Hello", name)
# Module import json # Open the json file and storing it as a dictionary in "data" # Change 'fr.json' by the path to your file with open('fr.json', encoding='utf8') as json_file: data = json.load(json_file) # Loading a second file with open('fr (1).json', encoding='utf8') as json_file: data2 = json.load(j...
# char type does nont exist in python # strings are made up of smaller string # I know, it's weird # strings are immutable # How do I format strings? # There are many ways to do it in python # For example, you can simply add them together hello = "Hello " world = "World!" print(hello + world) # A better way of doing ...
# -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here if n <= 0: return 0 pre = 1 next = 1 for i in range(3, n + 1): tmp = next next = pre + next pre = tmp return next
def email_at_domain (domain, email): if email.count('@') != 1 or email[0] == '@' or email.split('@')[1] != domain: print('Email ', email, ' is not valid at ', domain) else: print('Email ',email, ' is valid at ', domain ) some_domain = input('Enter domain: ') some_email = input('Enter email: ...
try: number_of_students = int(input('Enter the number of students in the class: ')) if number_of_students <=0: print('Invalid number of students. Try again!') raise SystemExit number_of_PCs = int(input('Enter the number of PCs in the lab: ')) if number_of_PCs <=0: print('really?...
NO_OF_CHARS = 256 def max_distinct_char(s, n): count = [0] * NO_OF_CHARS for i in range(n): count[ord(s[i])] += 1 max_distinct = 0 for i in range(NO_OF_CHARS): if (count[i] != 0): max_distinct += 1 return max_distinct def smallesteSubstr_maxDistictChar(s): n = len(s) max_distinct = max_distinct_char(s, n) ...
#Simulating Bird Flock Behavior in Python Using Boids #pip install p5 #to create some “boids” from p5 import setup, draw, size, background, run class Boid(): def __init__(self, x, y, width, height): self.position = Vector(x, y) #create another file named main.py and put the graphi...
# This is a game called tic tac toe # you can play with friend or AI # add score,reset and undo button import math import random import pygame import time pygame.init() pygame.display.set_caption("Tic Tac Toe") pygame.display.set_icon(pygame.image.load("icon.png")) win = pygame.display.set_mode((400, 500)) backgrou...
#!/usr/bin/python3 import sys import os from pathlib import Path import requests image_directory = './images/' def download_image(url): if url is not "": # removing trailing \n from urls url = url.rstrip("\n") try: # creating images directory if not exists os.make...
name = input("Please enter your name") #User input name as string print("Welcome to my world " + name) #Program outputs weclome
#!/usr/bin/env python import fileinput def mean(data): """Return the sample arithmetic mean of data.""" n = len(data) if n < 1: raise ValueError('mean requires at least one data point') #return sum(data)/n # in Python 2 use sum(data)/float(n) return sum(data)/float(n) mycount=0 mysum=0 f...
import json import xml from collections import defaultdict from operator import itemgetter import click import xmltodict from asciitree import LeftAligned def dict_map(dicty, key_fun=None, value_fun=None, tuple_fun=None): """Map the dict values. Example: >>> dts = lambda dicty: sorted(dicty.items())...
# Maggie Henry # ​CSCI 101 – Section G # Week 6 - Lab A - Lost Marbles # References: none # Time: 30 minutes print("Enter a string of X's and O's:") marble_string = str(input('MARBLES>')) marble_place = [] marble = "O" for i in range(len(marble_string)): if marble_string[i] == marble: marble_pl...
# Maggie Henry # ​CSCI 101 – Section G # Week 6 - Lab B - Unique Visitors # References: none # Time: 60 minutes print('Enter the users seperated by commas:') name_string = str(input('USERS>')) last_index = 0 name_list = [] i = 0 for i in range(len(name_string)): if name_string[i] == ',': split_...
from argparse import ArgumentParser from utils import parse_input def elevate(commands: str, stop_at=None): floor = 0 for i, command in enumerate(commands): if command == '(': floor += 1 else: floor -= 1 if stop_at is None: continue if floo...
import fileinput DEBUG = True def debug(*args): if DEBUG: print(*args) def parse_section(spec): a, b = spec.split('-') return int(a), int(b) def parse_line(line): first, second = line.strip().split(',') return parse_section(first), parse_section(second) def parse_input(): return...
x=int(input('Enter a 5 digit No.')) x=list(map(int, str(x))) z='' for i in x: y=i+1 z=z+str(y) print(z)
n=int(input('Enter any Number')) for i in range(2*n+1): for j in range(2*n+1): if(j==n): print('*',end=' ') elif(i==n and j!=n): print('*',end=' ') else: print(' ',end=' ') print()
""" " File: outlinergui.py " Written By: Gregory Owen " " Description: The GUI manager for outliner """ from Tkinter import * from outlinermenu import OutlinerMenu import dndlist class TopicLine(Frame): """ A frame that contains a label, a reference to a topic, a button to add a note to that topi...
Cities={ 'Karachi' : { 'Country':'Pakistan', 'Population': 21100000, 'Fact' : 'Karachi generates 35% of Pakistan’s Tax revenue' }, 'New York': { 'Country': 'United States of America', 'Population': 8538000, 'Fact': "In 2018 NYC will open the world's...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 9 03:38:29 2018 @author: """ # Recurrent Neural Network # Part 1.- Data Preprocessing #Import the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the training set dataset_train = pd.read_csv('Googl...
import turtle # Create our t1 turtle t1 = turtle.Turtle() t1.shape("turtle") t1.speed(0) t1.width(3) t1.color("yellow", "red") # Create our t2 turtle t2 = turtle.Turtle() t2.shape("turtle") t2.speed(0) t2.width(3) t2.color("blue", "orange") # Create our t3 turtle t3 = turtle.Turtle() t3.shape("turt...
import pymysql class DataBase: def __init__(self): self.connection = pymysql.connect( host='localhost', #ip user='root', # tu mombre de usuario DB password='sasa',# en mi caso db='demo'# nombre de tu DB ) self.cursor = self.connection.cursor(...
#!/usr/bin/env python # coding: utf-8 # In[ ]: def main(): s = str(input("Please enter the sentence: ")) numWords = len(s.split(" ")) average = 0 for n in s: average = average + len(n) average = (average - s.count(" "))/numWords print("Average Word Length:", len(s)) print("Nu...
''' Given a grid of dimension nxm where each cell in the grid can have values 0, 1 or 2 which has the following meaning: 0 : Empty cell 1 : Cells have fresh oranges 2 : Cells have rotten oranges We have to determine what is the minimum time required to rot all oranges. A rotten orange at index [i,j] can rot other fres...
# You are given an array arr[] of N integers including 0. The task is to find the smallest positive number missing from the array. class Solution: #Function to find the smallest positive number missing from the array. def missingNumber(self,arr,n): if len(arr)==1: if arr[0]==1: ...
# Calculate the angle between hour hand and minute hand. # Note: There can be two angles between hands, we need to print minimum of two. Also, we need to print floor of final result angle. For example, if the final angle is 10.61, we need to print 10. from math import floor class Solution: def getAngle(self, H ,...
# Given a Binary Tree, your task is to find its level order traversal. # For the below tree the output will be 1 $ 2 3 $ 4 5 6 7 $ 8 $. def levelOrder(root): result=[] result.append([root.data]) bfs(root,result) return result def bfs(root,result): q=[] part=[] q.append(root) ...
# Given two strings A and B. Find the characters that are not common in the two strings. def UncommonChars(A, B): s1=set(A) s2=set(B) commons='' for c in s1: if c not in s2: commons+=c for c in s2: if c not in s1: ...
# create a graph using adjacency list g = { 1: [2, 3], 2: [1, 4, 5], 3: [1, 6, 7], 4: [2, 8], 5: [2, 8], 6: [3, 8], 7: [3, 8], 8: [4, 5, 6, 7] } g1 = { 1: [2, 3], 2: [1, 4], 3: [1, 4], 4: [2, 3], 5: [6, 7], 6: [5, 7], 7: [6, 5] } # write code for breadth fir...
# Given a number N, calculate the prime numbers up to N using Sieve of Eratosthenes. # hint: Run a loop from 2 till sqrt of N considering every number as prime and mark the multiple of 2 as not prime. Then select next number which is prime then again marked its multiple as not prime. class Solution: def sieveOfEr...
# Segregate even and odd nodes in a Link List class Solution: def divide(self, N, head): evens=node() odds=node() p=head p1=evens p2=odds while p is not None: if p.data%2==0: p1.next=node() p1.next.data=p.d...
""" Given a grid of size n*n filled with 0, 1, 2, 3. Check whether there is a path possible from the source to destination. You can traverse up, down, right and left. The description of cells is as follows: A value of cell 1 means Source. A value of cell 2 means Destination. A value of cell 3 means Blank cell. A value ...
# For a given number N check if it is prime or not. A prime number is a number which is only divisible by 1 and itself. class Solution: def isPrime (self, N): if N==1: return 0 for i in range(2,int(N**0.5)+1): if N%i==0: return 0 return 1
# Square root of a number or floor of sqrt of x class Solution: def floorSqrt(self, x): return self.search(x) def search(self,x): start=0 end=x ans=-1 while start<=end: mid=(start+end)//2 if mid*mid==x : return mid ...
# Given a Binary Number B, find its decimal equivalent. class Solution: def binary_to_decimal(self, s): n=len(s)-1 result=0 for i in range(n+1): result+=int(s[i])*(2**(n-i)) return result
#You are given an array Arr of size N. You need to find all pairs in the array that sum to a number K. If no such pair exists then output will be -1. The elements of the array are distinct and are in sorted order. #Note: (a,b) and (b,a) are considered same. Also, an element cannot pair with itself, i.e., (a,a) is inval...
# A peak element in an array is the one that is not smaller than its neighbours. # Given an array arr[] of size N, find the index of any one of its peak elements class Solution: def peakElement(self,arr, n): if len(arr)==1: return 0 result=self.search(arr,0,len(arr)-1) ...
# Given a Binary Tree, find Right view of it. Right view of a Binary Tree is set of nodes visible when tree is viewed from right side. class Solution: #Function to return list containing elements of right view of binary tree. def rightView(self,root): result=[] maxLevel=[0] self.rv(root...
#Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it. In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... (considering the increasing lexicographical order). def convertToWave(self,A,N): for i in range(0,len(A),2): ...
# Given an array of N positive integers, find GCD of all the array elements. class Solution: def gcd(self, n, arr): currgcd=arr[0] for num in arr: currgcd=self.gcdOfTwo(currgcd,num) return currgcd def gcdOfTwo(self,A,B): if A==...
# Given two linked lists, your task is to complete the function makeUnion(), that returns the union of two linked lists. This union should include all the distinct elements only. def union(head1,head2): s=set() p=head1 while p is not None: s.add(p.data) p=p.next p=head2 ...
# Given a number N.Find if the digit sum(or sum of digits) of N is a Palindrome number or not. # Note:A Palindrome number is a number which stays the same when reversed.Example- 121,131,7 etc. class Solution: def isDigitSumPalindrome(self,N): S=0 while N!=0: d=N%10 ...
from random import randint from time import sleep while True: jogador = str(input('''VAMOS JOGAR JOKEN PO! [1] PEDRA [2] PAPEL [3] TESOURA QUAL VOCÊ ESCOLHE? ''')) if jogador == '1' or jogador == '2' or jogador == '3': computador = randint(1, 3) if jogador == '1': jogador = 'PEDRA' ...
n = input("Digite um número inteiro: ") tamanho = len(n) n = int(n) soma = 0 while (tamanho >= 1): soma = soma + (n % 10) n = n // 10 tamanho = tamanho - 1 print (soma)
Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "copyright", "credits" or "license()" for more information. >>> ================= RESTART: /home/user/RTR105/MonteCarlo.1.py ================= uniform(low=0.0, high=1.0, size=None) Draw samples from a uniform distribu...
import plotly.express as px import csv with open("Ice-Cream vs Cold-Drink vs Temperature - Ice Cream Sale vs Temperature data.csv") as csv_file: df = csv.DictReader(csv_file) fig = px.scatter(df, x="Ice-cream Sales", y="Temperature") fig.show()
#!/usr/bin/env python3 """ Sorting algorithms to write: - [X] Bucket sort - [X] Bubble sort - [ ] Insertion sort - [ ] Selection sort - [ ] Heapsort - [ ] Mergesort """ def bucket_sort(x, max_val=0): """ A variation of the bucket sort. Alg: Create an array as long as the max value in...
class Solution: def maxProfit(self, prices: List[int]) -> int: profit = 0 for i in range(len(prices)-1): if prices[i+1]>prices[i]: profit += prices[i+1] - prices[i] return profit ''' Pseuducode: ...
# Write a function that reverses a string. The input string is given as an array of characters char[]. # Do not allocate extra space for another array, # you must do this by modifying the input array in-place with O(1) extra memory def reverseString(s): left = 0 right = len(s)-1 while(left < right): ...
class File(object): """documentation for File. initialize with filename, read() returns the content of the file. """ def __init__(self, filename): super(File, self).__init__() self.filename = filename def read(self): content = "" with open(self.filename,'r') as ...
#https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/red_black_tree.py class RedBlackTree: def __init__(self,label=None,color=0,parent=None,left=None,right=None): # 0表示黑色,1表示红色 self.label = label self.parent = parent self.left = left self.right = right ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pandas as pd import numpy as np import datetime ###################### FEATURES BASED ON THE PAST OF THE PLAYERS ############### def features_past_generation(features_creation_function, days, fe...