text
stringlengths
37
1.41M
import linkedlist import unittest class Node: def __init__(self, value): self.value = value self.prev = None self.next = None def expectEmpty(self, linkedList): self.assertEqual(linkedList.head, None) self.assertEqual(linkedList.tail, None) def expectHeadTail(self, linkedList, ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # post-order is Left, Right, Root # this works by, if the value is a TreeNode, it means that is hasn't been visited yet. # when ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # recursive def isSymmetric(self, root: TreeNode) -> bool: def isSym(L, R): if L and R and L.val == R.val: ...
''' This program will calculate the desired population size given a desired confidence interval error and standard deviation. ''' import math as m def two_side_z(ci): if ci == 0.8: z = 1.28 elif ci == 0.9: z = 1.645 elif ci == 0.95: z = 1.96 elif ci == 0.98: z = 2.33 elif ci == 0.99: z = 2.58 return z...
want_place = ['beijing','shanghai','nanjing','shenzhen','guangzhou'] print(want_place) print(sorted(want_place)) print(want_place) print(sorted(want_place,reverse=True)) print(want_place) want_place.reverse() print(want_place) want_place.reverse() print(want_place) want_place.sort() print(want_place) want_place.sort(re...
foods = ('a','b','c','d','e') for food in foods: print(food) # foods[0] = 'r' print('------------------') foods = ('a','b','c','f','g') for food in foods: print(food)
dict = { 'a': 'aaa', 'b': 'bbb', 'c': 'ccc', 'd': 'ddd', 'e': 'eee' } for key in dict: print(f'{key}:{dict[key]}') for key in dict: print(f'{key}\n {dict[key]}')
nums = [i**3 for i in range(1,11)] print(nums) print(f'the first three items in the list are:{nums[0:3]}') print(f'three items from the middle of the list are:{nums[4:7]}') print(f'the first three items in the list are:{nums[-3:]}')
current_users = ['admin', 'B', 'c', 'd', 'e'] new_users = ['d', 'e', 'f', 'g', 'h', 'b'] # for new_user in new_users: # if new_user in current_users: # print('you need an other name.') # else: # print('this name has not used.') # 确保不区分大小写 current_users_lower = [current_user.lower() for current...
import pickle class Employee: def __init__(self,name=None,dob=None,dept=None,desn=None,sal=None): self.__name=name self.__dob=dob self.__dept=dept self.__desn=desn self.__sal=sal def get_name(self): return self.__name def get_dob(self): return self.__d...
from typing import List, Mapping, Type, Dict class Attribute(): """ Schema definition for a column in SQL Attributes ---------- identifier The SQL identifier. display_name The text to display when prompting for this value. is_primary If ...
userstring = input("Give me a number thats greater than 100") usernum = int(userstring): while usernum < 100: print(str(usernum) + " is less than 100, Try again, I've got all day...") userstring = input(usernum + " is less than 100, Try again, I've got all day...") usernum = int(userstring): print(usernum + " i...
def mergesort(arr): print arr if len(arr) > 1: half = len(arr) // 2 a = mergesort(arr[:half]) b = mergesort(arr[half:]) return merge(a, b) else: return arr def merge(a, b): print a, b i, j = 0, 0 ret = [] while i < len(a) or j < len(b): if i < len(a) and j < len(b): if a[i] ...
from add import add class Student: __name = "" def __init__(self,name): self.__name = name def getName(self): return self.__name if __name__ == "__main__": student = Student("liuchuanshi") print student.getName() print add.Add(1,22)
#!/usr/bin/env python3 import csv fname = 'user_statistics.csv' with open(fname) as file: reader = csv.DictReader(file) for row in reader: print("Name: {} INFO: {} ERROR: {}".format(row["Username"], row["INFO"], row["ERROR"])) fname = 'error_message.csv' with open(fname) as file: reader = csv.Dict...
#!/usr/bin/env python3 import re def compare_strings(string1, string2): #Convert both strings to lowercase #and remove leading and trailing blanks string1 = string1.lower().strip() string2 = string2.lower().strip() #Ignore punctuation punctuation = r"[.?!,;:-']" string1 = re.sub(punctuation, " ", string1...
""" informatics 113652 Определить можно ли с использованием только операций «прибавить 3» и «прибавить 5» получить из числа 1 число N (N - натуральное, не превышает 10^6). """ def naive(n): while n > 0: if n == 1: print('YES') break if n > 5: n =...
""" Циклически сдвиньте элементы списка вправо (A[0] переходит на место A[1], A[1] на место A[2], ..., последний элемент переходит на место A[0]). Используйте минимально возможное количество операций присваивания. """ def solution_1(a): """ попарные обмены 0 <> 1; 0 <> 2 и тд """ for ...
""" Переставьте соседние элементы списка (A[0] c A[1], A[2] c A[3] и т.д.). Если элементов нечетное число, то последний элемент остается на своем месте. """ def solution(array): for i in range(0, len(array) - 1 - len(array) % 2, 2): t = array[i] array[i] = array[i+1] array[i+1] =...
""" Дан список чисел. Если в нем есть два соседних элемента одного знака, выведите эти числа. Если соседних элементов одного знака нет - не выводите ничего. Если таких пар соседей несколько - выведите первую пару. """ def first_pair(array): ## flag = True ## i = 1 ## ## while flag: ## if...
""" Construa a função separaPal(string) que recebe como entrada um texto contendo um documento qualquer. A função deve retornar uma lista contendo palavras presentes no texto. Uma palavra é uma sequência de caracteres entre caracteres chamados de separadores. São considerados separadores os seguintes caracteres: Ponto...
""" Biblioteca criada com todas as funções criadas em Programação 2 """ """ Um n-grama é uma sequência de caracteres de tamanho n, por exemplo: "goiaba" --> 1-grama: g, o, i, a, b, a 2-grama: go, oi, ia, ab, ba 3-grama: goi, oia, iab, aba ... Construa a função ngrama(<texto>, <tam>) que retorna uma lista ...
""" Construa a função removeAcento(<texto>) que retorna uma versão de <texto> com os caracteres acentuados substituidos por seus equivalentes não acentuados """ def removeAcento(pTexto): strSemAcento = "aeiou" strComAcento = "áàâãéèêẽíìîĩóòôõúùûũ" novoTexto = ""; j = 0; i = 0 divisor = 4 while i < len(pTexto): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # removeStopW.py # # Copyright 2015 Cristian <cristian@cristian> """ Construir a função removeStopW(<texto>,<lista de stopwords>). A função devolve um a texto sem stopwords. """ import libplnbsi def removeStopW(pTexto, listaStopWords): resultado = [] if type(pTe...
#Try, Except, Else and Finally result = None x = int(input("Number 1: ")) y = int(input("Number 2: ")) try: result = x / y except Exception as e: print(e) else: print("Inside Else") finally: print("Inside Finally") print("---- New Line ----") print("Reslt = ", result)
def sumf(n1, n2): c = n1 + n2 return c num = sumf(10, 20) print(num) def sum(inp1, inp2): if type(inp1) == type(inp2): return inp1 + inp2 else: return "Datatypes are different." x = sum(10, 15) print(x) # --------- Arguments --------------- # # Positional Arguments # keyword Arg...
x = "hello world, after full stop" z = " hello world, after full stop a" V = "HELLO WORLD," print(x.capitalize()) print(x.split()) print(x.upper()) print(x.lower()) # indexing print(x[0]) print(x[0:7]) print(x) print(x.strip()) print(x.lstrip()) print(x.rstrip()) print(V.islower()) print(x.isupper()) print(x...
x = 0 print("\n") while x < 6: print(f"Current value of x: {x}") x = x + 1 else: print("Loop Completed") num = 1 sum = 0 while num != 0: num = int(input("\n \n Enter Number: ")) sum = sum + num print(f"Number: {sum}") else: print("Loop Completed")
# Aggregation, has a relationship, use the objects, class Salary: def __init__(self, pay, reward): self.pay = pay self.reward = reward def annual_salary(self): return (self.pay*12) + self.reward class Employee: def __init__(self, name, position, sal): self.name = name ...
class Student: def __init__(self, n): self.name = n print("2nd __init__ method.", self.name) def display(self): print("Hi") s1 = Student("Ana") s1.display()
import numpy as np def interp1du(x, x0, step, f): """ Interpolate linearly, under the assumption that the values in `f` are defined on a uniformly spaced grid [x0, x0 + step, x0 + 2*step, ...]. The implementation is based on code provided by Phillip M. Feldman in https://github.com/scipy/scipy/is...
# -*- coding: utf-8 -*- def last(lista): #Devuelve el ultimo elemento de la lista return lista[len(lista)-1] lista=[] tam=input("Ingrese el tamaño de la lista") for i in range(0,tam): lista.append(raw_input("Ingrese el elemento " + repr(i + 1))) print ("El último elemento de la lista es "+repr(last(l...
# -*- coding: utf-8 -*- def init(lista): #Retorna todo los elementos menos el ultimo listaAux=[] for i in range(0,len(lista)-1): listaAux.append(lista[i]) return listaAux lista=[] tam=input("Ingrese el tamaño de la lista") for i in range(0,tam): lista.append(raw_input("Ingrese el el...
# -*- coding: utf-8 -*- def secuencia1(m,n): listaAux=[] if n<m: return listaAux else : for i in range(m,n+1): listaAux.append(i) return listaAux num1=input("Ingrese el extremo 1 de la lista") num2=input("Ingrese el extremo 2 de la lista") print ("Secuencia:"...
import array import time import sys class SudokuSolver: """A 9 by 9 sudoku solver""" # Main side length MAJOR = 9 # Partition size length MINOR = 3 # Empty value EMPTY = 0 FORMATTING_GRID = """ ------------------------- | {} {} {} | {} {} {} | {} {} {} | | {} {} {} | {} {}...
## ASCII to unary from codigame "Chuck Norris" puzzle ## https://www.codingame.com/training/easy/chuck-norris ## solution by Antoine BECK 03-15-2017 import sys import math message = input() #input provided char_count = 0 #used to count the chars in input current_bit = ';' #current bit initialised to random not-a-bi...
a = int(input('vedite chislo')) q = int(pow(a, .5)) for b in range(q+1): print(b,'^2=', b**2)
class Pirate: def __init__( self , name ): self.name = name self.strength = 15 self.speed = 3 self.health = 100 self.bac = 1 def show_stats( self ): if Pirate.check_stats(self.health): print(f"Name: {self.name}\nStrength: {self.strength}\nSpeed: {sel...
# Ejercicio 1.1 - Alberto Raygada # Crear un programa que tome dos numeros y devuelva el mayor de ellos # ------------------------------------------------------------------------------------------------- num1 = int(input("Incluya el primer numero: ")) num2 = int(input("Incluya el segundo numero: ")) if num1 > num2: ...
#Basic Password Gen Made With Python #Password is "Password" from os import system, name import random import time import os import getpass char = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!£$%^&*" # The character list used to generate the password def masterPass(): coun...
class Node: def __init__(self, Data="Head", Next = None): self.Data = Data self.Next = Next class LinkList: def __init__(self): self.Head = Node() def get_length(self): cnt = 0 current_node = self.Head while current_node: cnt += 1 ...
from itertools import islice, count ''' Python 3.x ''' def print_all(collection): [print(element) for element in collection] def take(count, collection): return islice(collection, 0, count) def squares_of(collection): return (x*x for x in collection) class Integers: @staticmethod def all():...
import numpy as np import time def compute_error(b, m, data): e_total = 0 for i in range(0, data.shape[0]): x = data[i, 0] y = data[i, 1] e_total += (y - (m * x + b)) ** 2 return e_total / float(data.shape[0]) def compute_error_matrix(b, m, data): x, y = np.split(data, 2, axi...
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X:...
import word import wordValueTable import frequency_value_table try: import Queue as Q # ver. < 3.0 except ImportError: import queue as Q """ Class that makes an array of word objects and creates a sorted array of the words. The sorting is based on assigning a value to a word Attributes for word v...
import sqlite3 # This function contains the 4 options def dbOption(Option): if (Option == 1): # This statement can be removed later print("You chose Option 1: Find accepted papers.") # Implement Query 1 here: # List the titles of accepted papers in a given area, that hav...
import pygame, sys pygame.init() #Colors black = (0, 0, 0) white = (255, 255, 255) screen_size = (800, 600) screen = pygame.display.set_mode(screen_size) clock = pygame.time.Clock() player_width = 15 player_height = 90 #Coordenadas y velocidad del jugador 1 player1_x_coord = 60 player1_y_coord = 300...
''' Write a code which accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically. ''' input_string = input("Enter a String: ") print("Alphabetically sorted string: ", ''.join(sorted(input_string)))
""" There is class which initialize rays Rays are directions which can be attacked by sliced figures like Queen, Rook or Bishop """ import bitarray as bt from constants import * class RaysInitializer: @staticmethod def count_north_rays(): """ Count rays in north direction for...
class fib(): def __init__(self,n): self.a=0 self.b=1 self.num=n self.count=0 def __iter__(self): return self def __next__(self): if(self.count>self.num): raise StopIteration elif(se...
# 문자열을 숫자(정수)로 변환이 가능한지 체크하는 내용 A = [ '' ,'1' ,'1.1' ,'A' ,'a' ,'$' ,'가' ] # is함수 : 판독함수(그렇냐, 아니냐) for data in A: print( data,data.isalpha(), data.isdecimal(), data.isdigit(), data.isnumeric() ) # 외장함수 => 가져오는 절차 import가 반드시 같이 존재한다 # 모듈을 가지고와서 그안에 존재하는 함수를 사용하는 케이스 import random for n in range(10): # 난수범위는 :...
#Binary Tree class Node: pindex =0 head = None def __init__(self, data,p,h): self.data = data self.left = None self.right = None self.p = p self.height=h self.index =Node.pindex Node.pindex+=1 print('created '+str(data)) def insert(self,d...
import sys import math a=[]#contain BIds b=[]#priority def ins_sort(): for j in range(1,len(a)): i = j-1 temp1 = b[j] temp = a[j] print(str(temp)+" "+str(i)) while(i>=0 and a[i]>temp ): a[i+1]=a[i] b[i+1]=b[i] i-=1 i+=1 a[i...
class DoneException(Exception): pass def read_input(filename): def no_empties(x): return x is not None and x != '' with open(filename) as f_in: return filter(no_empties, [l.replace('\n', '').strip() for l in f_in.readlines()]) def to_value(line): return map(int, line.split(',')) def add(): retu...
class Recipes(object): def __init__(self): self.size = 0 self.first_recipe = None def __repr__(self): return "%s" % self.scores def scores(self): curr = self.first_recipe scores = [] for _ in range(self.size): scores.append(curr.score) ...
from utils import read_from_file, d_print from collections import defaultdict import math vertical = 1 horizontal = 0 class Puzzle(): def __init__(self, pieces): self.pieces = pieces self.dimensions = int(math.sqrt(len(pieces))) self.edge_map = self.generate_edge_map() self.piec...
def read_input(filename): with open(filename) as f: return f.readlines()[0].replace('\n', '') def part1(input): had_reaction = True polymer = input while(had_reaction): new_polymer = '' had_reaction = False i = 0 while i < (len(polymer) - 1): if poly...
class Coord(object): def __init__(self, x, y): self.x = int(x) self.y = int(y) self.is_finite = True def __str__(self): return "(%d, %d)" % (self.x, self.y) def __repr__(self): return self.__str__() def manhattan_distance(p1, p2): return abs(p1.x - p2.x) + a...
from collections import defaultdict def read_input(filename): def no_empties(x): return x is not None and x != '' with open(filename) as f_in: return filter(no_empties, [l.replace('\n', '').strip() for l in f_in.readlines()]) def to_value(line): return map(int, line.split('-')) def meets_criteria(pa...
import numpy as np import matplotlib.pyplot as plt def montaGrafico ( xResp, yResp, yPrev ) : """ Função que monta os gráficos """ plt.figure ( 0 ) plt.plot ( xResp, yResp, "--r", linewidth = 2 ) plt.xlabel("tempo (s)") plt.ylabel("Número de indivíduos") plt.title ( "Números de indiv...
from matplotlib import pyplot as plt from random import randint, random class Skyline: # MÈTODE CREADOR def __init__(self, param1, param2=None, param3=None, xmin=None, xmax=None, color=None, type=None, asigna_atribs=True): """ Mètode creador de la classe Skyline. """ # Creaci...
#!/usr/bin/env python3 # snake.py import gi, random gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GLib, Gdk field_size = 25 win_size = 800 speed = 100 init_parts = 3 class objects: x_coord = random.randint(0, field_size-1) y_coord = random.randint(0, field_size-1) def set_x_y(self,x: ...
#Modelling a decision tree to predict import numpy as np import itertools # splits a dataset into two based on the column value def divide_set(data, column, value): split_function = None if isinstance(value,int) or isinstance(value, float): # split_function = lambda row:row[column] >= value set1 = data[data[:,...
import requests from urllib.parse import quote, urljoin API_URL = "https://f.linggle.com/api/" __write_api_url = urljoin(API_URL, 'write_call') __aes_api_url = urljoin(API_URL, 'aes') __check_api_url = urljoin(API_URL, 'aes_dect') __suggest_api_url = urljoin(API_URL, 'suggest/') def suggest_pattern(text): """Thi...
largest = None print('Before: ',largest) for iterv in [3, 41, 12, 9, 74, 15]: if largest == None or iterv > largest: largest = iterv print('Loop:', largest,iterv) print('Largest:',largest)
sum = 0 ite = 0 while True: inp_n = input('Enter a number:') try: num = float(inp_n) sum = sum + num ite = ite + 1 except: if inp_n == 'done': break else: print('Invalid input') try: print(sum,ite,sum/ite) except: print(sum,ite)
province = input("What province do you live in? ") # tax = 0 # this was initially in the code but it is not necessary if province == 'Alberta': tax = 0.05 elif province == 'Nunavut': tax = 0.05 elif province == 'Ontario': tax = 0.13 else: tax = 0.15 print(tax)
''' Created on May 16, 2013 @author: Yubin Bai ''' class Solution: # @param board, a list of lists of 1 length string # @param word, a string # @return a boolean def exist(self, board, word): # backtrack def _search(x, y, step, word): if step == len(word): ...
''' Created on 2013-5-19 @author: Yubin Bai ''' class Solution: # @param A, a list of integers # @param target, an integer to be searched # @return an integer def search(self, A, target): left = 0 right = len(A) - 1 while(left <= right): mid = (left ...
# Given n, how many structurally unique BST's (binary search trees) that # store values 1...n? # For example, # Given n = 3, there are a total of 5 unique BST's. # 1 3 3 2 1 # \ / / / \ \ # 3 2 1 1 3 2 # / / \ ...
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: ...
entradas = [-1, 7, 5] pesos = [0.8, 0.1, 0] def soma(e, p): s = 0 for x in range(3): # print(entradas[x]) # print(pesos[x]) s += e[x] * p[x] return s s = soma(entradas, pesos) print(s) def stepFuncion(soma): if soma > 1: return 1 return 0 r = stepFuncion(s) ...
from datetime import datetime from abc import ABC, abstractmethod class Order(ABC): def __init__(self, date, number, customer): self._date = date self._number = number self._customer = customer def ChangeCustomerName(self, newName): self._customer.SetName(newName) @ab...
#!/usr/bin/env python import os,sys """ DATA EXTRACTOR Extracts the data of file 1 requested from file 2 """ # Defining data dictionary data_dic ={} # Opening input files data_file = open(sys.argv[1]).readlines() query_file = open(sys.argv[2]).readlines() # Defining index data_index = int(sys.argv[3]) query_index ...
#!/usr/bin/env python import os, sys """ FASTA to FASTQ converter """ # Opening input file input_data = open(sys.argv[1]).readlines() new_object = ["",""] circ_dict = {} """ FUNCTION: converter OBJECTIVE: convert FASTA to FASTQ x: refers to data n: refers to new_object """ def converter(x, n): # Defining key...
# You are going to write a virtual coin toss program. It will randomly tell the user "Heads" or "Tails" import random random_select = random.randint(0,1) if random_select == 0: print("Tails") else: print("Heads")
#Nested if / else Explanation print ("Welcome to the rollercoaster!") height = int(input("What is your height in cm? ")) if height >= 120: print("You can ride the rollercoaster! Yea!!!!") age = int(input("How old are you? ")) if age < 12: print("You have to pay $5.00") elif age >= 12 and age...
#Data Types #STRING print("Hello"[0]) # Subscripting pull out a particular element from a string #Fast Exercise print the last char from Hello print("Hello"[4]) #Integer print(123+345); 123_456 #Float 3.14159 #Boolean True False
import time start_time = time.time() def isPrime(num): if(num <= 1): return False i = 2 while(i*i <= num): if(num % i == 0): return False i += 1 return True def makeSleeve(num): sleeve = [True]*(num+1) if(num == 1): return [False, False] sleeve...
n = int(input("Input an int: ")) # Do not change this line div_num = 1 factor = 0 while div_num <= n/2: if n % div_num == 0: factor = n / div_num print(factor) div_num += 1 # Fill in the missing code below
import random from tkinter import * class PirateNameGenerator(): origFirst = "" origLast = "" firstList = ["Fluffbucket", "Squidlips", "Scallywag", "Landlubber", "Sharkbait"] lastList = ["Chumbucket", "Swashbuckler", "McStinky", "Hornswaggler", "Barnacle"] def __init__(self, firstName, ...
from collections import defaultdict class Graph: def __init__(self, vertices): # No. of vertices self.vertices = vertices # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def add_edge(self, u, v): self.graph[...
import pandas as pd def transform_to_supervised(df, previous_steps=1, forecast_steps=1, dropnan=True): """ Transforms a DataFrame containing time series data into a DataFrame containing data suitable for use as a supervised learning problem. Derived from code originally found at htt...
#!/usr/local/bin/python3 # route.py : Find routes through maps # # Code by: surgudla-sgaraga-bgogineni # # Based on skeleton code by V. Mathur and D. Crandall, January 2021 # # !/usr/bin/env python3 #importing required libraries import heapq import math import sys #Function to read and load read and loa...
def compareStrings(input, output): if input.lower() == output.lower(): return input.lower() return ':(' print(compareStrings('Marc LOVES hanging off the sideof buildings','marc loves hanging off the sideof buildings')) print(compareStrings('James is writing his FIRST react app','james is writing a reac...
# --- Instructions: # Must use OOP. You should build your program in a modular way, so that once you have the basic structure set up, it is easy to add additional questions and/or sections. # There must be at least 3 sections of the survey. Each section must have a title and description, and a minimum of 3 mult...
## --- Instruction: calculate check digit def calculate_credit_card_check_digit(card_number): list_of_digits = list(card_number[::-1]) sum = 0 for digit in range(0,len(list_of_digits)): if digit % 2 == 0: digit_times_two = int(list_of_digits[digit]) * 2 if digit_times_two > ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'file comment.' __author__ = 'soonfy' print('npm test.') name = input('name') print(name) print('your name is %s, age is %d.' %(name, 18)) print(10.25 / 5) print(12 / 5) print(10 / 5) print(12.25 // 5) print(12 // 5) print(12.25 % 5) print(12 % 5) if name == 'sf': ...
# Ejemplo de Multiple Linea Regression # Data Preprocessing import numpy as np # Mathematical tools import matplotlib.pyplot as plt import pandas as pd # Import and Manage Data Sets dataset = pd.read_csv('50_Startups.csv') # independent variables X = dataset.iloc[:, :-1].values # Matrix of features [filas,columna...
''' 1. write a short python code to display your name amd department ''' name = "Abdullahi Usman Musa" department = "computer science" print('Name:',name,"\n"'Department:',department) ''' 2. Assign the string 'boo!' to the variable scare and print the variable ''' scare = 'boo!' print(scare) ''' 3. Add ...
# line graph import matplotlib.pyplot as plt input_values = [1, 2, 3, 4, 5] squares = [1, 4, 9, 6, 30] # change the style of the graph's background plt.style.use('seaborn') fig, ax = plt.subplots() # change to the line to bold ax.plot(input_values, squares, linewidth=3) # set chart title and label axes ax.set_titl...
import threading import time# 子執行緒,也就是你第二個需要執行的程式 ''' time.sleep(2) def job_2(): print('thread %s is running...' % threading.current_thread().name) for i in range(5): print("-----second program------:", i) time.sleep(2) # 設定子執行緒 t = threading.Thread(target = job_2)# 執行他 t.start() print('first thread %s is runni...
searched = 66 list1 = [1, 3, 5, 55, 66, 77, 160] leftIndex = 0 rightIndex = len(list1)-1 middleIndex = int(rightIndex/2) while list1[middleIndex]!=searched and rightIndex>leftIndex: if list1[middleIndex] < searched: print("middle become left", list1[middleIndex]) print("right the same", list1[rightI...
""" Given a string representing a stock ticker, return the stocks alphabetized. Example: Given the following input: "AAPL 313 GOOG 513 TSLA 58 BBY 22" Your function should return: "AAPL 313 BBY 22 GOOG 513 TSLA 58" ["AAPL 313", "BBY 22", "GOOG 513", "TSLA 58"] 1. Split out pairs of stock names, prices 2. Sort by na...
import copy def reverse_only_positives(arr): """Given an array of numbers, reverse only the positive numbers. For instance, [-3, -2, -1, 0, 1, 2, 3] -> [-3, -2, -1, 0, 3, 2, 1] Hint: l is a copy of arr, which I think will help solve the problem. """ # TODO: Modify and return l l = copy.deepcopy(arr) ...
# This function has an O(N^2) runtime. Can you rewrite it such that it has an O(N) runtime, but the same input and output? def f(my_list): total = 0 for i in range(len(my_list)): for j in range(i, len(my_list)): total += my_list[j] return total def new_f(my_list): return
## Case-study #1 # Developers: Zhuravlev Aleksandr (30), # Starnovskiy Sergey (50), # Drachev Nikita(30). import turtle import time def square(x, y, size,color, tilt): #function drawing square #param x: first coordinate of left angle #:param y: second coordinate of left angle...
def fives(arr): for x in arr: if x % 5 == 0: print(x) a = [10, 20, 33, 46, 55] fives(a)
def income(num): if num < 10000: return 0 elif num <= 20000: return (num - 10000) * 0.1 else: a = 10000 * 0.1 b = (num - 20000) * 0.2 return a + b print(income(45000))
def tups(arr1, arr2): result = set() x = 0 while x < len(arr1): temp = (arr1[x], arr2[x]) result.add(temp) x += 1 return result a1 = [2, 3, 4, 5, 6, 7, 8] a2 = [4, 9, 16, 25, 36, 49, 64] print(tups(a1, a2))