text
stringlengths
37
1.41M
# Build a machine learning model to predict salary based on position for a given dataset #https://drive.google.com/open?id=1jKfNxQkybZKprVpCkoL16mTjmSSnCol3 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import Lin...
# Write a Python program to create a stacked bar plot with error bars. #Note: Use bottom to stack the women?s bars on top of the men?s bars. #Sample Data: #Means (men) = (22, 30, 35, 35, 26) #Means (women) = (25, 32, 30, 35, 29) #Men Standard deviation = (4, 3, 4, 1, 5) #Women Standard deviation = (3, 5, 2, 3, 3) imp...
#Write a Python program to find the list of words that are longer than n from a given list of words #Method 1 a=[] n=int(input("Enter the number of elements in list of words:")) # Loop for appending element to list a for x in range(0,n): element = input("Enter element" + str(x + 1) + ":") a.append(element) m...
# Write a Python program to create an array which looks like below array. #Expected Output: #[[ 0. 0. 0.] #[ 1. 0. 0.] #[ 1. 1. 0.] #[ 1.,1.,1.] import numpy as np print(np.tril(np.ones((4,4),dtype=int),-1))
#Write a program to draw a scatter plot for a given dataset and show datalabels on hover #https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv import plotly import plotly.plotly as py import plotly.graph_objs as go import numpy as np import pandas as pd plotly.tools.set_credentials_file(usern...
#Write a Python program to convert a NumPy array into Python list structure. #Expected Output: #Original array elements: #[[0 1] #[2 3] #[4 5]] #Array to list: #[[0, 1], [2, 3], [4, 5]] import numpy as np a= np.arange(6).reshape(3,2) print("Original Array Elements:",a) print("Array to List:") print(a.tolist())
#Write a program to draw a scatter plot of “day” against “total bill” for a dataset given in a url # https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv import seaborn as sns import matplotlib.pyplot as plt tips=sns.load_dataset("tips") print(tips) x=sns.scatterplot(x="total_bill",y="day",data=t...
x=[[5,1,3], [1,1,1], [1,2,1]] y=[1,2,3] def matmul(m, v): rows = len(m) w = [0]*rows irange = range(len(v)) sum = 0 for j in range(rows): r = m[j] for i in irange: sum += r[i]*v[i] w[j],sum = sum,0 return w a=matmul([[5, 1, 3], [1, 1, 1], [1, 2, 1]],...
#Write a Python program to find the number of elements of an array, length of one array element in bytes and total bytes consumed by the elements. #Expected Output: #Size of the array: 3 #Length of one array element in bytes: 8 #Total bytes consumed by the elements of the array: 24 import numpy as np x=np.array([1,2...
#Create a 3x3 matrix with values ranging from 2 to 10. #Expected Output: #[[ 2 3 4] #[ 5 6 7] #[ 8 9 10]] import numpy as np x=np.arange(2,11).reshape(3,3) print(x) print(type(x)) print(x.shape)
# Stack implemented in python class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.item...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 14 21:42:22 2018 Gaussian elimination Solve A*X = B A = N*N matrix X = solution B = N*1 or 1*N matrix @author: Apiwat Wisitsorasak """ import numpy as np # Input #A = np.array([[2.0,1.0,-1.0],[-3.0,-1.0,2.0],[-2.0,1.0,2.0]]) # Coefficient matrix #...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 8 20:15:39 2018 @author: Apiwat Wisitsorasak This program reads a 1D simulation data from TASK/TR output and plot it. The graph is also export as a EPS figure. """ import matplotlib.pyplot as plt import math def PlotGraph1D(filename1, XLabel, YLa...
def sortLibsvmKeys(inputPath,outputPath): ''' This function requires an inputPath string and an outputPath string The input file must already be in libsvm format as shown below label key:value key:value key:value ....... The sorted libsvm file will be write to outputPath ''' ...
# Jeff Bromen """Simple Python script to set an alarm for a specific time. When the alarm goes off, a random youtube video will be opened. The possible youtube video URLs are taken from "youtube_alarm_videos.txt" With snooze option and wake up text added by Franek """ import datetime import os impo...
# Write a program to find the sum of the squares ofall natural numbers from 1 to N def squaresum(n) : #define function sm = 0 #initialise sm to zero for i in range(1, n+1) : sm = sm + (i * i) #sm is updating by adding square of no.s return sm n =int(input(...
""" This module is for FIT3162 (Final Year Project of Monash University) and created for data preprocessing purposes. It contains the following methods : a) preprocess_data :- reads in a DATA file or csv file and preprocesses the dataset b) clean_data :- impute missing values in an attribute/feature c) att...
import numpy as np import argparse import re OPERATORS = { 'AND': np.logical_and, 'OR': np.logical_or, 'NOT': np.logical_not, 'XOR': np.logical_xor, } def pre_processUnaryOperation(matrix, index_documents, index_words, terms): """ - Description: Convert the query terms into binary operators, with...
""" Tools for working with files """ import sys def read(file): """ Read contents of file. """ with open(file) as f: return f.read() def open_input(file_path): """ Open input file, accepting "-" as a magic token for "stdin" """ return open(file_path, "r") if file_path != "-" e...
class LineReader: def __init__(self): self._lines = [] self._num = 0 self._len = len(self._lines) @property def lines(self): return list(self._lines) @property def length(self): return self._len def __iter__(self): self._num = 0 retur...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 10 20:10:00 2019 Integers, floats, methods for numeric data and casting """ # Aritmetic operations print(3 + 2) print(3 - 2) print(3 * 2) print(3 / 2) print(3 // 2) print(3 ** 2) print(3 % 2) #sequence pf opertations is same as BODMAS # changing a...
# Chapter 4 # Lists and tuples # 🎯 1.LISTS a = [1,4,7,53,29] print(a) # Indexing start from 0 print(a[0],a[1],a[-1]) # IndexError: list index out of range #print(a[6]) # You Can Change the list items,mutable... a[3] = "Changed :)" print(a) # We can create a list items with different data Types b = [34,"Harryb...
def enter_results(player1, player2): """ User enters results of the round. Returns Tuple of 2 lists ([player1, score1], [player2, score2]) """ player1_score = 0.1 player2_score = 0.1 score_list = [0.0, 0.5, 1.0] while not (player1_score + player2_score == 1 and player1_score in score_list a...
# Ask the user for their name print('What is your name?') name = input() # This stores the input into a variable into a variable called name print(type(name)) # Type tells you what data type the variable is. The type is str (short for string). print() # Ask the user for their age print('What is your age?') age = int(i...
def binarySearch(arr,k): """ Use case: searching a sorted array for a value Best case: on any sorted array, binary search is preferred over linear search Time Complexity Best case: O(1) -- k happens to be the middle element Average case: O(log(n))-- repeated halving of s...
zahl = int(input("Bitte Zahl eingeben:")) if (zahl % 3 == 0 and zahl % 7 == 0): print("Die Zahl", zahl, "ist durch 3 und 7 teilbar.") else: print("Nix da")
""" Multilayer Perceptron. A Multilayer Perceptron (Neural Network) implementation example using TensorFlow library. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/). Links: [MNIST Dataset](http://yann.lecun.com/exdb/mnist/). Author: Aymeric Damien Project: https://...
h = float(input("身長何cmですか?"))/100 w = float(input("体重何kgですか?")) bmi = w / (h*h) print("あなたのBMI値は、",bmi,"です。")
import sqlite3 from employee import Employee conn = sqlite3.connect(':memory:') c = conn.cursor() c.execute("""CREATE TABLE employees( first text, last text, pay integer )""") def insert_emp(empl): with conn: c.execute("INSERT INTO employees VALUES(:first, :last, :pay)", {'first': empl.first, 'last':...
import helpers # Professores # modelo = { # nome: # cpf: # departamento: # } professores = [] def adicionar(nome, cpf, departamento): professor = {} for professor_consulta in professores: if cpf == professor_consulta["cpf"]: return False professor["nome...
from Card import Card, Deck from Player import Player, Dealer class Game(): def __init__(self, player, dealer, deck): self.player = player self.dealer = dealer self.deck = deck def play(self): # print("Credits: {}".format(self.player.credits)) print(self.dealer) ...
def reverse(x): z=[] xmax=len(x) ll=list(x) for y in range (0,xmax): z.append(ll[xmax-1-y]) k="".join(z) return (k) print (reverse('cinzia'))
from tkinter import * root=Tk() myLabel=Label(root, text="Hello World!") myLabel.grid(row=0, column=0) myLabel2=Label(root, text="Trinità!") myLabel2.grid(row=0, column=1) myLabel2=Label(root, text="Caspita!") myLabel2.grid(row=1, column=2) root.mainloop()
import tkinter root = tkinter.Tk() root.title("BMI Calculator") root.geometry("250x100") def calculate_bmi(): kg = float(entry_kg.get()) height = float(entry_height.get()) bmi = round(kg/(height**2),2) label_result['text'] = f"BMI:{bmi}" if bmi > 26: label_result['text'] = f"Overweight:{bm...
p = float(input("Enter preassure in pascal = ")) v = float(input("Enter volume in liter = ")) t = float(input("Enter temperature in celcius = ")) n = (p * v) / (8.314 * (273.15 + t)) print("%.2f moles of gas in the tank" %n )
int = int(input("Enter integer = ")) if int % 2 == 0: result = "Even" else: result = "Odd" print(result)
fresh = int(input("Number of fresh bread = ")) old = int(input("Number of day-old bread = ")) total_fresh = fresh * 3.49 total_old = old * 3.49 * 0.6 total = total_old + total_fresh print("Fresh bread = $ %.2f" %total_fresh) print("Day-old bread = $ %.2f" %total_old) print("Grand total = $ %.2f" %total)
year = int(input("Enter year = ")) a = year % 19 b = year // 100 c = year % 100 d = b // 4 e = b % 4 f = (b + 8) // 25 g = (b - f + 1) // 3 h = ((19 * a) + b - d - g + 15) % 30 i = c // 4 k = c % 4 l = (32 + (2 * e) + (2 * i) - h - k) % 7 m = (a + (11 * h) + (22 * l)) // 451 month = (h + l - (7 * m) + 11...
side = int(input("Enter number of side = ")) if side == 3: shape = "Triangle" elif side == 4: shape = "Rectangle" elif side == 5: shape = "Pentagon" elif side == 6: shape = "Hexagon" elif side == 7: shape = "Heptagon" elif side == 8: shape = "Octagon" elif side == 9: shape = ...
vol = float(input("Enter volume of water in liter = ")) t1 = float(input("Enter current temp in celcius = ")) t2 = float(input("Enter desire temp in celcius = ")) m = vol * 1000 dt = t2 - t1 q = m * 4186 * dt price = 8.9 * q * 0.0000002778 print("To heat %.2f liter of water to %.2f celcius you'll need %.2f...
#Lab 3 Adolfo Flores, Dr. Olac Fuentes #CS2302 1:30p.m., Anindita Nath, Maliheh Zargaran #Last Edited 3/11, BST management algorithms class BST(object): # Constructor def __init__(self, item, left=None, right=None): self.item = item self.left = left self.right = right ...
from tkinter import * root = Tk() root.geometry("970x570") root.title("Password Generator") root.wm_iconbitmap("password.ico") root.resizable(0, 0) Label(root, text="Welcome to Password Generator", font=("Times", 35, "bold underline"), fg="green").pack() Label(root, text="Enter length of Password: ", font=("...
# 45. Write a Python program to find the index of an item of a tuple. sample_tuple = (19,22,32,45,76,24,76) index_of_32 = sample_tuple.index(32) print(index_of_32)
# 10. Write a Python program to remove the characters which have odd index # values of a given string. def string_manipulation(string): result = string[0::2] return result if __name__=="__main__": test_string = input('Enter the string: ') res = string_manipulation(test_string) print(res)
# 46. Write a Python program to find the length of a tuple sample_tuple = (32,45,32,5,6,7,8,8,21,43,65,15,15,54) length_of_tuple = len(sample_tuple) print(length_of_tuple)
# 22. Write a Python program to remove duplicates from a list. def remove_duplicates_list(list_items): result = list(set(list_items)) return result if __name__=="__main__": res = remove_duplicates_list([2,4,5,5,3,2,2,4,1,1,1]) print(res)
# 27. Write a Python program to replace the last element in a list with another list. def replace_element(list1, list2): result = list1[:-1] + list2 return result if __name__=="__main__": list1 = [1, 3, 5, 7, 9, 10] list2 = [2, 4, 6, 8] res = replace_element(list1, list2) print(f'List1...
#!/usr/bin/python3 from math import cos, sin import math class Projectile(): def __init__(self, x, y, vel, ang): self.x = x self.y = y self.vel = vel self.ang = ang self.g = -9.8 print(self.get_duration()) print(self.get_max_height()) print(self.get_ra...
# 姓名 = [] # 電子郵件 = [] # x=input("請輸入姓名 :") # 姓名.append(x) # y=input("請輸入電子郵件 :") # 電子郵件.append(y) # x=input("請輸入姓名 :") # 姓名.append(x) # y=input("請輸入電子郵件 :") # 電子郵件.append(y) # x=input("請輸入姓名 :") # 姓名.append(x) # y=input("請輸入電子郵件 :") # 電子郵件.append(y) # mane = input('請輸入要查詢電子郵件的姓名') # num1 = {姓名[0]:電子郵件[...
a = int(input("請輸入座號?")) if (a % 5) == 0 : print("組別為",(a//5)) else: print("組別為",((a // 5)+1)) # if 條件判斷式 # else 動作2(如果不是if執行else) # input 輸入
import csv from math import sin, cos, sqrt, atan2, radians # distance.py returns the # what is location? def haversine(my_location, location): # approximate radius of earth in km R = 6373.0 lat1 = radians(my_location[0]) lon1 = radians(my_location[1]) lat2 = radians(float(location[0])) lon2 = radians(float(loc...
import math def isprime(num): count=2 while count<=math.sqrt(num): if num%count==0: return False count+=1 return True i,mulitiply=1,1 while mulitiply<=10**6: i+=1 if isprime(i): mulitiply*=i print mulitiply/i
import math def isprime(n): count=2 for count in range(2,int(math.sqrt(n))+1): if n%count==0:return False return True def isoddcomposite(n): if not isprime(n): return True else: return False num=9 while True: if isoddcomposite(num): prime=1 for j in range(1,1+int(math.sqr...
# """ # # import time # # try: # f = open('test.txt') # # try: # while True: # content = f.readline() # if len(content) == 0: # break # time.sleep(2) # print(content) # except: # # 如果在读取⽂文件的过程中,产生了了异常,那么就会捕获到 # # ⽐比如 按下了...
# Question 1 # def fahrenheit_to_celsius(input_in_F): # fahrenheit = float(input_in_F) # celsius = (fahrenheit - 32) * (5/9) # print(f"{celsius:.2f}") # input_in_F = input("Enter temp in F: ") # # fahrenheit_to_celsius(input_in_F) # Question 2 # def calculate_mean(total_sum, num_items): # mean = (...
import random from timeit import default_timer as timer def sequential_search(a_list, item): start = timer() pos = 0 found = False while pos < len(a_list) and not found: if a_list[pos] == item: found = True else: pos = pos+1 end = timer() return (found, ...
import sys class Solution: # @return a tuple, (index1, index2) def findMin(self, num): low = 0 high = len(num)-1 mid = 0 while low < high: mid = (low + high) / 2 if num[mid] > num[high]: low = mid + 1 else: high...
#!/usr/bin/env python2.7 """ Columbia W4111 Intro to databases Example webserver To run locally python server.py Go to http://localhost:8111 in your browser A debugger such as "pdb" may be helpful for debugging. Read about it online. """ import os from sqlalchemy import * from sqlalchemy.pool import NullPool...
#Problem statement at: https://www.hackerrank.com/challenges/30-review-loop/problem # Enter your code here. Read input from STDIN. Print output to STDOUT def oddEven(s): even=[] odd=[] s = list(s) for j in range(len(s)): if(j%2==0): even.append(s[j]) else: odd.ap...
#Problem Statement at: https://www.hackerrank.com/challenges/30-running-time-and-complexity import math def isPrime(num): if (num > 1): for i in range(2,int(math.sqrt(num))+1): if(num%i==0): return("Not prime") return("Prime") else: return 'Not prime' T = i...
#Problem Statement: https://www.hackerrank.com/challenges/30-binary-numbers #!/bin/python3 import math import os import random import re import sys def cal_consecutive1s(n): l = [] while(n>=1): r = int(n%2) l.append(r) n = n/2 l = l[::-1] #print(l) count = 0 max_=0 ...
import random def play(): print("****************************") print("WELCOME TO THE GUESSING GAME") print("****************************") secret_number = random.randrange(1, 101) maximum_of_attempts = 0 score = 1000 print("(1) Easy (2) Medium (3) Hard") difficulty_level = int(input...
""" 8クイーン問題 """ N = 8 cnt = 0 # 盤面を可視化 def view_field(col): field = [] # 2次元リストマップを作成 for i in range(N): sub_field = [] for j in range(N): sub_field.append(".") field.append(sub_field) # "Q"を埋めていく for y, x in enumerate(col): field[y][x] = "Q" # 盤面を...
""" フォルダにあるファイルを探す 深さ優先探索 """ import os def search(dir, name): for i in os.listdir(dir): if i == name: print(dir + i) if os.path.isdir(dir + i): if os.access(dir + i, os.R_OK): # 読み込み可能か search(dir + i + '/', name) search('/', 'book') # パス名、フォルダ名
""" 力任せ法 一致している場合は、1文字ずつ追加しながら比較する 一致しない場合は、1文字ずらして改めて比較する """ text = list('SHOEISHA SESHOP')#文字列をリストに変換 pattern = list('SHA')#確認したい文字列 for i in range(len(text)): match = True for j in range(len(pattern)): if text[i + j] != pattern[j]: match = False break if match:#一致していれば最...
class Employee: def __init__(self, id, name): self.id = id self.name = name def display(self): print(f"ID: {self.id} \nName: {self.name}") # Creating a emp instance of Employee class emp = Employee(1, "coder") emp.display() # Deleting the property of object del emp.id # Deleting the...
import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--physics", help="physics marks") parser.add_argument("--chemistry", help="chemistry marks") parser.add_argument("--maths", help="maths marks") args = parser.parse_args() print(args.physics) ...
from functools import reduce def flatten(input_list: list) -> list: """ flattens a list (possibly containing nested lists) :param input_list: list to be flattened :return: flattened list (straight list w/ no nested lists within). If empty list is given, an empty list is returned """ if not...
x = 0b101 # 5 y = 0x0a # 10 z = x + y # 15 # 0b - двоичная # 0a - восьмериричная # 0x - шестнадцетиричная print("{0} in binary {0:08b} in hex {0:02x} in octal {0:02o}".format(z)) # 0:08b: номер переменной, 0b - двоичная, 8 - число знаков после запятой
class Person: @property def age(self): return self.__age @age.setter def age(self, age): if age in range(1, 100): self.__age = age else: print("Недопустимый возраст") tom = Person() tom.age = -3486 tom.age = 36 print(tom.age) # sett...
def isUnical(l): for i in range(0, len(l) - 1): for j in range(i + 1, len(l) - 1): if l[i] == l[j]: return False return True l = input("введите значения для списка через пробел ").split() print(isUnical(l))
def counter(): num = 0 def incrementer(): # nonlocal num num += 1 return num return incrementer c = counter() print(c()) # nonlocal указывает на то, что эта переменная не является локальной, # следовательно, ее значение будет взято из ближайшей области видимости, в которой # суще...
FILENAME = "forTask5.txt" l = list() def count_char(text, char): count = 0 for c in text: if c == char: count += 1 return count try: with open(FILENAME, "r") as file: text = file.read() for char in "abcdefghijklmnopqrstuvwxyz": perc = 100 * count_char(...
#Page 203, Figure 13.4(バグなし) def walk(f, d, numSteps): """f: Field クラスのオブジェクト d: Drunk クラスのオブジェクト numSteps: 0 以上の整数 dをnumSteps回移動し, 酔歩の初期位置と最終位置との差を出力する. """ start = f.getLoc(d) for s in range(numSteps): f.moveDrunk(d) return start.distFrom(f.getLoc(d)) def simWalks(numStep...
x = 25 epsilon = 0.01 numGuess = 0 low = 0.0 high = max(1.0, x) ans = (high + low) / 2.0 while abs(ans ** 2 - x) >= epsilon: print('low =', low, 'high =', high, 'ans =', ans) if ans ** 2 < x: low = ans else: high = ans ans = (high + low) / 2.0 numGuess += 1 print(ans, 'is close to s...
import matplotlib.pyplot as plt import environment from environment import Noise class EnvRandom(environment.Environment): def __init__(self, ndim=1, noise_dist=Noise.normal, seed=None): """ Initializes the environment including an initial state. """ super(EnvRandom, self).__ini...
import random #our board in dictionary form board = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' ' } g_numx_win = 0 g_numo_win = 0 g_num_tie = 0 g_times = 0 g_turn = ['X', 'O'] #print our board def printBoar...
def main(): num = int(input("Insira o valor:")) if num % 2 == 0: print("O número é par!") else: print("O número é ímpar!") main()
import math t = int(input()) def solve(n,numbers): ans = 'NO' for number in numbers: aux = int(math.sqrt(number)) if number != (aux*aux): ans = 'YES' break return ans for i in range(t): n = int(input()) numbers = list(map(int,input().split(' '))) ans ...
n=int(input()) for y in range(0,n): num=input() count=0 for t in range(0,len(num)): count=count+int(num[t]) print (count)
from abc import ABC, abstractmethod from design_patterns.factory.services.transportation import Truck class TransportationCreator(ABC): """ This is the abstract creator :return: returns the desired transportation method """ @abstractmethod def create_transport(self): pass cla...
""" Module to parse a number-string to a float or decimal. """ import re __version__ = "0.1.4" def sign_string(string, sign=1): """ Determine what sign the string should be based on if it is wrapped within parenthesis. """ try: # Try to unwrap numbers wrapped in ()s for match in r...
def sum_two_smallest_numbers(numbers): #numbers.sort() return sorted(numbers)[:1] print(sum_two_smallest_numbers([5, 8, 12, 18, 22]))
import numpy as np #defining the queue class to use as a data structure class queue(): def __init__(self): self.pending = list() def add(self, child): self.pending.insert(0, child) def remove(self): if self.pending: return self.pending.pop() return None de...
import sys import random import operator from random import randint from clean import clean from histogram import dic_histogram, dic_histogram_test, list_histogram # Declare the source of knowledge #source_text = sys.argv[1] source_text = 'fish.txt' # Clean up the source of knowledge raw_corpus = clean(source_text) ...
class Cuadruplo: # Funcion que inicializa a la clase cuadruplo def __init__(self): self.operador = '' self.operando1 = 0 self.operando2 = 0 self.resultado = "" # Funcion que permite establecer el valor del operador de un cuadruplo def set_operador(self, operador): ...
class Draw(object): char = 'x' width = 0 height = 0 canvas = [] def __init__(self, width, height, *args, **kwargs): super(Draw, self).__init__(*args, **kwargs) self.width = width + 2 self.height = height + 2 self.set_canvas() self.draw_canvas() ...
""" Exercise 1 – Dictionary reversals The candidate is required to implement the function reverse_dict which receives as input a dictio- nary D1 and returns a dictionary D2, whose content will have as keys the values of D1 and as values those keys of D1 the values are assigned to. Example: D1 = { ”MIO”: 102, ”ADS”...
""" Write a function that returns True if two arrays, when combined, form a consecutive sequence. A consecutive sequence is a sequence without any gaps in the integers, e.g. 1, 2, 3, 4, 5 is a consecutive sequence, but 1, 2, 4, 5 is not. Examples consecutive_combo([7, 4, 5, 1], [2, 3, 6]) ➞ True consecutive_combo([1, ...
""" The Skyline Problem A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. The geometric information of each building is given in ...
""" # Rocket Methods - Start with a copy of the Rocket class, either one you made from a previous exercise - Add a new method to the class. This is probably a little more challenging than adding attributes, but give it a try. - Think of what rockets do, and make a very simple version of that behavior using print st...
""" Given an english text return it with the words in reverse order """ def reflect(text, dcset): reflection = '' while text[-1] in dcset: reflection += text[-1] text = text[:-1] return ''.join((reflection, text)) def reverse(text, sep=' ', dcset=None, newline='\n'): dcset = dcset if...
def radixSort(arr): divisor=10 div=1 while(True): new=[[],[],[],[],[],[],[],[],[],[]] for i in arr: mod = i % divisor mod = mod / div new[mod].append(i) divisor *= 10 div *= 10 if len(new[0]) == len(arr): ...
'''Reverse a singly linked list. ''' class Node: def __init__(self, key): self.cargo = key self.next = None class linkedList: def __init__(self,cargo): self.head=Node(cargo) self.length=1 def addList(self,cargo): temp=self.head while(temp.next): ...
def raise_to_power(base_number,power_number): result=1 for i in range(power_number): result = result*base_number return result num1 = int(input("enter 1st one: ")) num2 = int(input("enter 2nd one: ")) print(raise_to_power(num1,num2))
import matplotlib.pyplot as plt import numpy as np import os import operator import pickle import sys import time def calculate_distance(self): all_distances = [] for house in self.houses.values(): x_house, y_house = house.x, house.y house_diff = {} counter = 0 for battery in s...
''' Programa que tenha uma lista chamada numeros e duas funções chamadas sorteio e somapar. A primeira função vai sortear 5 numeros e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores pares sorteados pela função anterior''' from random import randint from time impo...
''' Crie uma tupla com os 20 primeiros colocados da tabela do BR. Depois mostre a - apenas os 5 primeiros colocados b - os ultimos 4 colocados da tabela c - lista com os times em ordem alfabética d - em que posição tá a chapecoense''' print('**' * 20) print('{:^40}'.format(' Tabela do Brasileirão ')) p...
import time start_time = time.time() start = 13 results=[] memo = {} # initialize the memo dictionary def collatz_seq(n): if not n in memo: # check if already computed if n == 1: # if not compute it memo[n] = 1 ...
class Unique: def __init__(self, lst, ignore_case = False): self.lst = list(lst) self.index = -1 self.ignore = ignore_case def __next__(self): if self.index == len(self.lst)-1: raise StopIteration arr = set(self.lst) self.lst = list(arr) if se...