text
stringlengths
37
1.41M
import re import math import time import numpy as np import matplotlib.pyplot as plt #to hierarchical clustering with Eucledean distance. #cluster distance is average distance #agglomerative algorithm #to implement a hierarchical cluster algorithm #check if a point is in an list of points def pointIn(p, ps): res...
#primeiro exemplo de funções def meuverso(palavras): print(palavras) print(palavras) print(gato) def gato_duplo (parte1, parte2): gato = parte1 + parte2 meuverso (gato) linha1= "miau" linha2= "grrr miau" gato_duplo(linha1,linha2)
def gradient_descent(formula, init, epoch, lr, delta=1e-8): """formula: f(1), f(2), f(3) w: the weight of init epoch: the epoch for iterations lr: the step""" for i in range(epoch): f1 = formula(init - delta) f2 = formula(init + delta) g = (f2 - f1) / (2 * delta) ...
#-*-coding=utf-8-*- import os my_name = 'zeb' my_height = 78 my_age = 19 my_eyes = 'Blue' print(f"Let's talk about {my_name}.") tatal = my_age * 3 print(f"if i {my_name} and age is {my_age}") types_of_people = 10 x = f"there are {types_of_people} types of people." binary = "binary" do_not = "don't" y =...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-02-19 17:26:31 # @Author : ZubinGou (zebgou@gmail.com) # @Link : https://github.com/ZubinGou # @Version : $Id$ import os # 1 def make_inc(n): return lambda x: x + n f = make_inc(98) print(f(99)) print(f(0)) # 2 sum = lambda a, b, c: a + b + c pr...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-02-20 17:42:06 # @Author : ZubinGou (zebgou@gmail.com) # @Link : https://github.com/ZubinGou # @Version : $Id$ import os the_count = list(range(1, 6)) print(the_count) fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dim...
#!/usr/bin/env python import os, sys fb = open('input.txt', 'r') text = fb.read().split('\n')[:-1] # print(text) def run_file(text): i = 0 acc = 0 lines = [] while(i < len(text)): if i in lines: # print("infinite loop detected!") return else: line...
# Process: # Import necessary libraries # Get spreadsheet location and name # Store values in variables # Make the input text of the name of the stock uppercase # Present a small menu which will allow to either edit, add, or view # Create functions for each with proper logic import openpyxl import os from openpyxl i...
from __future__ import print_function import sys #class for the parsed instructions, add type, target for extra fuinctionality class instruction3ac : def __init__(self, no, type, in1, in2, out) : if type == 'cmp': debug(in1=in1,in2=in2,out=out) self.no, self.type, self.in1, self.in2, self.out = no, ...
myList = ['Sofia','carlos','mauricio','Rafa','Fabian','Beatriz','Pablo','Edgar','Santiago'] myList2 = ['Pepe','lepu'] #size = len(myList) #print(myList) #myList.sort(reverse=True,key=len) #print(sorted(myList))s #print(myList.pop(0)) #print(myList[3:9]) #myList.append('Renato') #print(myList) #myList.remove('Beatriz') ...
#message = input("introduce un mensaje") #print("This is the message:" , message) '''eset es un comentario de mas de una linea waoooooo ''' ''' number1 =int (input('give me the first number')) number2 = int (input('give me the second number')) _sum = number1 + number2 if _sum == 10: print('okay u got ten') elif...
from board import Board from game_tile import GameTile class GameBoard(Board): def __init__(self, width, height, num_mines): super().__init__(width, height, num_mines) self.total_selections = 0 self.mine_selected = False def add_tiles_to_board(self): for i in range(self.height)...
# Program to display the Fibonacci sequence up to n-th term nSequence = int(input("How many sequences do you wish to complete? ")) # first two numbers in the sequence num1, num2 = 0, 1 # initializing a counter count = 0 # check if the number of squences is valid if nSequence <= 0: print("Please enter a...
"""输入一个整数 k (k < 50), 输出一个 k*k 的九宫图。 示例: 5*5 17 24 01 08 15 23 05 07 14 16 04 06 13 20 22 10 12 19 21 03 11 18 25 02 09 """ import random def exch(arr, a, b): tamp = arr[a] arr[a] = arr[b] arr[b] = tamp def shuffle(arr): """Rearrange array so that result is a uniformly random permutation. ...
#*****Funciones 7***** print('\nFunciones Ejercicio # 07\n') def calcularpresupuesto(presupuesto): presu_ginecologia = presupuesto * 0.40 presu_traumatologia = presupuesto * 0.30 presu_padiatria = presupuesto * 0.30 return presu_ginecologia, presu_traumatologia, presu_padiatria presupue...
#*****Funciones 4***** print('\nFunciones Ejercicio # 04\n') def preciofinal (precio): precio = precio * (1+0.30) return precio costo = float(input(('Ingrese el costo del artículo-->¢'))) resultado = preciofinal(costo) print(f'\nLa tienda compra el artículo a ¢{costo} y lo vende a ¢{resulta...
class Node: def __init__(self, label, *children): self.label = label self.children = children def __str__(self): chstr = [str(i) for i in self.children] chstr = ', '.join(chstr) return "Node {}: [{}]".format(self.label, chstr) class Leaf: def __init__(self, label, val): self.label = labe...
#!/usr/bin/env python3 # This program is an example for running a motor at a set power value. # The motor will turn with a constant torque, at whatever RPM allows it. # # Created by the Purdue ENGR 16X teaching team # Contact a TA if you have any questions regarding this program. # # Hardware: Connect EV3 or NXT motor...
from pprint import pprint class Player(): def __init__(self, name, card1, card2, bank, dealer=False): self.cards = [card1, card2] self.name = name self.bank = bank self.dealer = dealer self.score = self.__calculate_cards_value__() if (dealer): self.cards[...
# Filename: wall_area_of_room2 # Created by: jasongreen # Date: Saturday, January 12, 2019 # Time of Creation: 12:07 # --- # calculate wall area of room NOT # including two windows and a door # I'm sure I could do this in an array, but don't know how. room_perimeter = int(i...
import sys def get_fuel(mass): """ Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. For example: For a mass of 12, divide by 3 and round down to get 4, then subtr...
#this script adds course entries to the classes_for_prototype.csv file #so that we can have some discussion sections in our test data import random import csv courses_input = [] with open("intermediate_data_file.csv", "rU") as data: reader = csv.reader(data) for row in reader: #print(row) cou...
# -*- coding: utf-8 -*- import random import string import sys notPrintable = {'🔾', '🔿', '🕀', '🕁', '🕂', '🕃', '🕄', '🕅', '🕆', '🕇', '🕈', '🕨', '🕩', '🕪', '🕫', '🕬', '🕭', '🕮','📾'} viableCharacters = [chr(i) for i in range(0x1F300, 0x1F578) if chr(i) not in notPrintable] viableCharacte...
# As an exercise , add a method __sub__(self, other) that overloads the subtraction operator, and try it out. class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __sub__(self, other): return self.x - other.x, self.y - other.y p = Point() p1 = Point(2, 4) p2 = Point(4,...
import numpy as np from helper import * def sigmoid(x): # Sigmoid activation function: f(x) = 1 / (1 + e^(-x)) return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x): # Derivative of sigmoid: f'(x) = f(x) * (1 - f(x)) fx = sigmoid(x) return fx * (1 - fx) def relu(x): # Relu function: f(x) = x ...
import sys def reverse_word(word): reversed_word = [] ''' turn the string into list ''' array = list(word) ''' reverse by getting the index of the last character to the first''' index = len(word)-1 while index >= 0: reversed_word.append(array[index]) index -= 1 return rever...
# -*- coding: utf-8 -*- """ Created on Wed Feb 26 16:19:56 2020 @author: vidhy""" #---------------------------------------The knapsack problem--------------------------------------------------- import numpy as np import pandas as pd import random as rd from random import randint import matplotlib.pyplot as...
from random import shuffle, randrange from time import sleep from structures import Tree, RBTreeNode BLACK = RBTreeNode.BLACK RED = RBTreeNode.RED NIL = RBTreeNode.NIL def tree_insert(tree, data): node = RBTreeNode(data) node.left = node.right = NIL tree_insert_node(tree, node) def tree_insert_node(tre...
# MNIST handwritten digit recognition problem # Simple NN with one hidden layer # For plotting ad hoc MNIST instances from keras.datasets import mnist import matplotlib.pyplot as plt # For NN import numpy from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.la...
class BinarySearch(list): def __init__(self, a, b, *args): list.__init__(self, *args) self.list_length = a self.step = b end = self.list_length * self.step for i in range(self.step, end+1, self.step): self.append(i) @property def lengt...
"""Scoring, analysing This file includes functions to analyse the tweets and give them scores. """ import re import os def get_words(): """Get words Returns a list with first a list of positive words and second a list of negative words. """ # path to the directory including the w...
import zipfile import shutil f = open('fileone.txt', 'w+') f.write('ONE FILE') f.close f = open('filetwo.txt', 'w+') f.write('TWO FILE') f.close comp_file = zipfile.ZipFile('comp_file.zip', 'w') comp_file.write('fileone.txt', compress_type = zipfile.ZIP_DEFLATED) comp_file.write('filetwo.txt', compress_type = zipfil...
import deck import card import hand def black_jack(): deck1 = deck.Deck() balance = 1000 print("Welcome to Black Jack!\n") while True: win = 0 playerturn = 0 dealerturn = 0 print(f"Current Balance: ${balance}") if balance <= 0: print("You are out ...
import requests import bs4 result = requests.get("https://en.wikipedia.org/wiki/Jonas_Salk") print(type(result)) # print(result.text) soup = bs4.BeautifulSoup(result.text, "lxml") # print(soup) print(soup.select('title')) site_paragraphs = soup.select("p") print(site_paragraphs) print(site_paragraphs[0])
# imports all openGL functions from OpenGL.GL import * from OpenGL.GL import shaders from matutils import * # we will use numpy to store data in arrays import numpy as np class Uniform: """ We create a simple class to handle uniforms, this is not necessary, but allow to put all relevant code in one place ...
import unittest class Node: def __init__(self, keyIn, valueIn): self.key = keyIn self.value = valueIn self.left = None self.right = None def __repr__(self): return "Node{ key : " + str(self.key) + ", value : " + str(self.value) + "}" def getKey(self): retur...
#!/usr/bin/env python # -*- coding: utf-8 -*- # function: https://practice.geeksforgeeks.org/problems/coin-change/0 # author: jmhuang # email: 946328371@qq.com # date: 2018/7/1 import sys global matrix def calculate_coin_change(number, number_list): global matrix if number == 0: return 0 if not ...
import requests from datetime import datetime def get_proxies(request="getproxies", proxytype="http", timeout="10000", country="all", ssl="all", anonymity="all"): """ returns a list of proxies as strings ['host1:port1', 'host2:port2'] or None if proxies aren't found. proxytype - http, socks4, and socks5 ...
from math import sqrt import numpy as np from sympy import Matrix def get_pos_array(key,alphabet): """ Gets an array of positions of a string in the alphabet Params: key - word to be transformed alphabet - alphabet that contains the key Return: An array of positions """ ...
import unittest from calculator import Calculator class TestStringMethods(unittest.TestCase): def test_expression(self): calc = Calculator("1,2") self.assertEqual(calc.expr, "1,2") def test_invalid_expression(self): with self.assertRaises(RuntimeError): Calculator("a,b") ...
earnings = float(input("Введите значение выручки:")) expenses = float(input("Введите значение издержек:")) if earnings > expenses: print("Прибыль — выручка больше издержек") profit = earnings - expenses efficiency = profit / earnings print("Рентабельность составляет %.2f" % efficiency) employers = ...
# Реализовать функцию int_func(), # принимающую слово из маленьких латинских букв и возвращающую его же, # но с прописной первой буквой. # Например, print(int_func(‘text’)) -> Text. # # Продолжить работу над заданием. # В программу должна попадать строка из слов, разделенных пробелом. # Каждое слово состоит из латински...
# Реализовать функцию, принимающую несколько параметров, # описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон. # Функция должна принимать параметры как именованные аргументы. # Реализовать вывод данных о пользователе одной строкой. def pretty_user_print(first_name, last_name,...
class StackMin: def __init__(self): self.stack = [] def add(self, item): minval = self.getmin() minval = min(minval, item) self.stack.append((item, minval)) def getmin(): if len(self.stack) == 0: return inf("float") return self.stack[-1][1] ...
""" One Away: There are threetypes of edits that can be performed onstrings:insert a character,removea character, orreplacea character.Given two strings, write a function to check if they are one edit(orzero edits) away. EXAMPLE pale, pIe -> true pales,pale -> true pale,bale -> true pale, bake -> false """ class Solu...
# Call Center: Imagine you have a call center with three levels of employees: Respondent, # manager, and director. An incoming telephone call must be first allocated to a respondent who is free. # if the responder can't handle the call, he or she must escalate the call to a manager. # if the manager is not free or not...
# [15,16,19,20,25,1,3,4,5,7,10,14], key = 5 # mid # left = 0 # right = len(arr) - 1 # mid = left + right//2 # mid = left + (right-left)/2 # compute the mid value # if arr[mid] < arr[left], we know that the left side is not sorted and we need to explore the right side first and then the left side ...
# Testing assigned variables and output. x = 5 y = 7 z = x + y print ("z is equal to", z, "by addition. \nThanks!") z = y - x print ("z is equal to", z, "by subtraction. \nThanks!") # Testing conditional flow control max = x if(x > y) else y print( '\nGreater value is', max)
import networkx as nx for i in range(10): print(i) # Iterate through list - a bit more Pythonic z = [42, 15, 9, 'italy', 14] for z_item in z: print(z_item) # iterate through a dict z2 = {42: "tyger", 15: "burning", 9: "bright", 3: "yeats"} for z_key in z2: print(z_key, z2[z_key])
Name = input("What is your Name ") Branch = input("What is your Branch ") College = input("What is your college Name ") Gender = input("What is your Gender ") Age = input("What is your Age ") print(Name + "\n" + Branch + "\n" + College + "\n" + Gender + "\n" + Age)
# tasks guessing game # 0 # Hangman-0.png # Word: hangman # Guess: E # Misses: # 1 # Hangman-1.png # Word: _ _ _ _ _ _ _ # Guess: T # Misses: e # 2 # Hangman-2.png # Word: _ _ _ _ _ _ _ # Guess: A # Misses: e, t # 3 # Hangman-2.png # Word: _ A _ _ _ A _ # Guess: O # Misses: e, t # option+ cmd + L import re def chec...
def recurse_dict (value, bag_dict, already_counted) : if value not in already_counted : count = 1 already_counted.append(value) else : count = 0 if value not in bag_dict : return already_counted, count arr = bag_dict.get(value) for i in arr : already_counted,...
import json import urllib.request CONVERSION_FACTIOR = 250 # Main function which will run loop until there are no new pages to read in API def main(): weights = [] url_base = "http://wp8m3he1wt.s3-website-ap-southeast-2.amazonaws.com" url_api = "/api/products/1" while True: url = ...
# Google image web scraper for Nostalgia Machine project # Adapted from: # https://github.com/hardikvasa/google-images-download/issues/301#issuecomment-587097949 # and # https://towardsdatascience.com/image-scraping-with-python-a96feda8af2d # ###########################################################...
# # Example file for working with date information # from datetime import date from datetime import time from datetime import datetime def main(): ## DATE OBJECTS # Get today's date from the simple today() method from the date class oToday = date.today() daynames = ["mon","tue","wed","thu","fri", "sat", "sun"]...
import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset= pd.read_csv('50_Startups.csv') X=dataset.iloc[:,:-1].values Y=dataset.iloc[:,4].values #encoding strings into numbers from sklearn.preprocessing import LabelEncoder ,OneHotEncoder labelencoder_X= LabelEncoder() X[:,3]=labe...
def str_interval(x): """Return a string representation of interval x. >>> str_interval(interval(-1, 2)) '-1 to 2' """ return '{0} to {1}'.format(lower_bound(x), upper_bound(x)) def add_interval(x, y): """Return an interval that contains the sum of any value in interval x and any ...
print('Please enter some sentences. Type "quit" on a line by itself to quit.') total = int(0) average = int(0) list1 = [] word_list=[] num_word=0 x=input('') while x != "quit": list1.append(x) x=input('') for sentance in list1: word_list=sentance.split() num_word+=len(word_list) ...
# -*- coding=utf-8 -*- # Implementation of Charikar simhashes in Python # See: http://dsrg.mff.cuni.cz/~holub/sw/shash/#a1 # 把文字转化为hash class SimhashBuilder: def __init__(self, word_list=[], hashbits=128): self.hashbits = hashbits self.hashval_list = [self._string_hash(word) for word in word_list]...
# -*- coding:utf-8 -*- import numpy as np import random # Object oriented approach class RandomWalker: def __init__(self): self.position = 0 def walk(self, n): self.position = 0 for i in range(n): yield self.position self.position += 2*random.randint(0, 1) - 1 ...
# -*- coding:utf-8 -*- import numpy as np import pandas as pd def data_filter_sort(data_path): # 引入数据 chipo = pd.read_csv(url_local, sep='\t') # 把price列转换为float格式 dollarizer = lambda x: float(x[1:-1]) chipo['item_price'] = chipo['item_price'].apply(dollarizer) # 删除掉重复的数据 chipo.filtered =...
# -*- coding:utf-8 -*- from pyhanlp import * # 用户自定义词典 class CustomisedDict: def __init__(self): self.CustomDictionary = JClass("com.hankcs.hanlp.dictionary.CustomDictionary") # def add(self, word): # self.CustomDictionary.add(word) def add(self, word, nature_with_freq=None): sel...
import numpy as np import matplotlib.pyplot as plt from scipy.odr import * import random def odr_demo(): # Initiate some data, giving some randomness using random.random(). x = np.array([0, 1, 2, 3, 4, 5]) y = np.array([i ** 2 + random.random() for i in x]) # Define a function (quadratic in our case)...
# -*- coding:utf-8 -*- import pandas as pd import numpy as np from scipy.spatial import Delaunay import matplotlib.pyplot as plt from scipy.spatial import ConvexHull def spatial(): # Delaunay三角 points = np.array([[0, 4], [2, 1.1], [1, 3], [1, 2]]) tri = Delaunay(points) plt.triplot(points[:, 0], point...
#Simple Caesar cypher. from string import * from collections import deque def key(n): #Slightly round-about way of generating the lookup-table, in order to preserve case lower = deque(ascii_lowercase) upper = deque(ascii_uppercase) lower.rotate(n) upper.rotate(n) return list(lower)+list(upper) def encrypt(s, n)...
from math import factorial def pascal(n,k): n, k = n-1, k-1 if k>n: return "No such number" return factorial(n)//(factorial(k)*factorial(n-k)) print(pascal(*map(int, input().split())))
#Functional programming killed the Python from itertools import chain, zip_longest dataz = [] for _ in range(int(input())):#Read input lines from stdin dataz.append(input()) words = list(chain.from_iterable(map(str.split, dataz))) + list(chain.from_iterable(map(str.split, map(''.join, zip_longest(*dataz, fillvalue=...
""" ## Problem1 Kth Smallest Element in a BST (https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/) Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Example 1: Input: root = [3,...
""" // Time Complexity :O(n) where n=number of words // Space Complexity :O(1) two hashmaps will store 26*2 keys // Did this code successfully run on Leetcode :Not LC problem // Any problem you faced while coding this : """ class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if (len(s)!=len(t)): ...
def bracket (a,f,s=0.01,m=2): #f é para avaliar, #s é o passo, m é o multiplicador para acelerar o processo. bracket = [a] #criando vetor com o intervalo desejado. # a=-2 #print("\nprimeiro bracket:",bracket) b = a + s # é um ponto b tal que é a soma de a + o passo, para avaliar se o próximo ponto é...
print("printing all alphabets from a-z") initialASCIIValue=int(input()) finalASCIIValue=int(input()) while(initialASCIIValue>0): print(chr(initialASCIIValue)) initialASCIIValue=initialASCIIValue+1 if(initialASCIIValue==finalASCIIValue): break
initialValue=int(input("Enter the Number : ")) inputNumber=int(input("Enter the Number : ")) sumValue=0 for number in range(initialValue,inputNumber+1): if(number>1): for i in range(2,number): if((number%i) == 0): break else: sumValue=sumValue+number ...
def firstDigit(number): while(number>=10): number=number/10 return int(number) def lastDigit(number): while(number>0): return number%10 number=int(input("Enter the Number : ")) firstDigit(number) lastDigit(number) print("Sum of First and last digit is :",(firstDigit(number)+lastDig...
digit=int(input("Enter the number : ")) temp=digit count=0 while(temp>0): temp=temp//10 count=count+1 print("Number of digits in number is :", count)
from arrays import Array2D # Open the text file for reading. grade_file = open( "grade.txt", "r" ) # Extract the first two values which indicate the size of the array. num_students = int( grade_file.readline() ) num_exams = int( grade_file.readline() ) # Create the 2 -D array to store the grades. exam_grades = Array2D...
import sqlite3 def LoadDataBase(name): conn=sqlite3.connect(name) cur=conn.cursor() cur.execute("CREATE TABLE Usuarios(email text primary key, name text, password text);") conn.commit() conn.close() def save(email, name, password): conn=sqlite3.connect("DataBase") cur=conn.cursor() cur...
""" Calculates the minimum edit distance between two strings. In other words, minimum number of operations to convert a to b. Also known as the Levenshtein algorithm. Arguments: 1. a: string 2. b: string 3. cost: (cost of making an edit) int {default 1} """ from memoize import memoize @memoize def minimum_edit_dist...
import time import re # main() calculates number of possible passwords def main(): meet = 0 doubles = False ascending_sequence = True initial_time = time.time() try: with open("data.txt", "r") as input: given_range_str = input.read() given_range_list = re.split("-", gi...
import MapReduce import sys """ @ jim pizagno 06.06.2014 This code will take data from a sparse matrix "a" and multiply it times sparse matrix "b". """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: column of final matrix # value: row/c...
# Bonus: # cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. # For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. # # def cons(a, b) -> int: return lambda f: f(a,b) def cdr(f): return f(lambda a, b: a) def car(f): return f(lam...
from itertools import groupby # Question 1.6 # Implement a method to perform basic string compression usng the counts of repeated characters. # # (1) Grouping by chars with groupby(string) # (2) Counting length of group with sum(1 for _ in group) (because no len on group is possible) # (3) Joining into proper format...
import numpy as np import time #Fibonacci para python def Fibonacci(N): if(N<2): return 1 else: return (Fibonacci(N-1)+Fibonacci(N-2)) #sacar tiempo para comparar, se hace un for para guardar N y el tiempo para cada iteracion enes=[] tiemposenes=[] for i in range(36): enes.append(i) t0=time.time() Fibonac...
# =========== define objective function for unsupervised competitive learning ========== def bingo(y_true, y_pred): # y_true can be ignored # find the biggest 3 outputs threshold = np.partition(y_pred, -3)[-3] # last 3 elements would be biggest loss = map( lambda y: if y >= threshold...
""" @author JungBok Cho @version 1.0 """ import time # Word list file WORDSLIST = "words.txt" # Pairs file PAIRLIST = "pairs.txt" # Dictionary to store every word dictionary = dict() # Minimum and Maximum of word length wordMin, wordMax = 4, 6 def readWordsFile(): """ Function to read w...
# 0 = not cute / 1 = cute N = int(input()) cute = 0 notcute = 0 for i in range(1, N+1) : opinion = int(input()) if opinion == 1 : cute += 1 elif opinion == 0 : notcute += 1 if cute > notcute : print('Junhee is cute!') else : print('Junhee is not cute!')
print('QUESTÃO 05') def acoes_bolsa(lista): d1 = 0 d4 = 4 s= sum(lista[d1:d4]) for c in range(len(lista)-3): soma = sum(lista[d1:d4]) d1 += 1 d4 += 1 if soma > s: s = soma return s print(acoes_bolsa([-1,-2,-3,-4,-5,-6,-7,-8]))
import turtle turtle.shape('turtle') finn = turtle.clone() finn.shape('square') finn.color('yellow') finn.goto(100,0) finn.goto(100,100) finn.goto(0,100) finn.goto(0,0) charlie = turtle.Turtle() charlie.shape = ('triangle') charlie.color('blue') charlie.goto(100,100) charlie.goto(200,0) charlie.goto(0,0) finn.goto(-4...
""" N,M이 주어진다. M은 입력으로 주어지는 연산의 개수 M개의 줄에는 각각의 연산이 주어진다 '팀 합치기' 연산은 0, a, b 형태로 주어진다. 이는 a번 학생이 속한 팀과 b번 학생이 속한 팀을 합친다는 의미 '같은 팀 여부 확인' 연산은 1, a, b 형태로 주어진다. 이는 a번 학생과 b번 학생이 같은 팀에 속해 있는 지를 확인하는 연산이다 a,b는 N 이하의 양의 정수이다 '같은 팀 여부 확인' 연산에 대하여 한줄에 하나씩 yes 혹은 no로 결과를 출력한다 """ # 특정 원소가 속한 집합을 찾기 def find_parent(parent, x): ...
#!/usr/bin/env python3 # Return the number of unique pairs from a list that sum up to a given integer def numberOfPairs(a, k): uniques = set() for i,x in enumerate(a): idx = 0 for y in a[i:]: if x == y and idx == 0: idx += 1 elif x + y == k ...
import pprint import pandas as pd import math import numpy as np """ The program implements the ID3 algorithm to generate the decision tree for classification and the decision tree would be saved in a dictionary in hierarchy structure. This is not a generalize program to receive any data format. It ...
import collections class SymbolTable(collections.MutableMapping): def __init__(self): """Initialize the symbol table to a stack with global scope""" self.stack = [] self.push() return def push(self): """Pushes and returns an empty dictionary onto the symbol table""" ...
""" CMSC 12300 / CAPP 30123 Task: Descriptive analysis (Exploring Questions) Main author: Sanittawan (Nikki) """ import csv import re from mrjob.job import MRJob class GetMaxAnsQuest(MRJob): """ A class for finding questions with the most number of answers per year from 2008 to 2019 using a MapReduc...
def listtGenerator(): lst1 = [] for i in range(10,100): lst1.append(i) i += 1 return lst1 def Generate_table(number): n = 1 lst = [] for i in range(10): i = n*number n = n+1 lst.append(i) return lst def WrongTable(table): import random ran...
""" A simple PyQt5 UI example Created by: Jacob Lewis Date: June 8th, 2016 """ import sys import numpy as np from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * V_NUM = "0.1" class CircleCanvas(QGraphicsView): """ Renders the circle """ def __init__(self, circleChec...
s=str(input('introduceti un nume si un prenume:')) a,b=s.split() print(a) print(b) if((a.title()==a)and(b.title()==b)): print('numele introdus este corect') else: print('numele introdus este incorect')
sexo = input('Informe o seu sexo: ') if(sexo== 'f'): print('O sexo Informado foi o sexo feminino.') elif(sexo== 'm'): print('O sexo informado foi o sexo masculino.') else: print('Sexo não detectado.')
import urllib.request, urllib.parse, urllib.error import json url=input("Enter location: ") #url = ' http://py4e-data.dr-chuck.net/comments_10141.json' #open url url_open = urllib.request.urlopen(url) #extract data data = url_open.read() #put the data into a dictionary data_parsed = json.loads(data) ...
def flat_list(nested_lst, low, high): lst = [] if isinstance(nested_lst, list): for i in range(low, high+1): if isinstance(nested_lst[i], list): lst.extend(flat_list(nested_lst[i], 0, len(nested_lst[i])-1)) else: lst.append(nested_lst[i]) else:...
def rightView(root): if not root: return queue=[] queue.append(root) while queue: l=len(queue) while l: temp=queue[0] if l==1: print(temp.data,end=" ") l-=1 if temp.left: queue.append(temp.left) ...
import sqlite3 import random class SimpleSQL3: """Table/db created upon init If working with an existing DB, leave the column_dict kwarg blank - column names will be populated automatically. database_name: looks for suffix '.db' - will add '.db' if not found. This can be overridden with the ...