text
stringlengths
37
1.41M
# Setup data structures trips = [9, 11, 13, 15, 10, 12, 14, 16] upPosition = 0 downPosition = 0 trainCapacity = [480, 480, 480, 480, 480, 480, 480, 480] income = [0, 0, 0, 0, 0, 0, 0, 0] # While there is more inputs # Display the departures board # Output outbound journeys # For x = 0 to 3 # Output departure time h...
#-*-coding:utf-8-*- # 简单的条件判断语句 # 1:if...else... # sex=input('请输入你的性别:') # if sex=='女': # print('一起shopping吧!') # else: # print('一起打球吧!') # task_score=int(input('请输入你的分数:')) # absence=int(input('请输入你的缺勤次数:')) # if task_score==100 and absence==0: # print('恭喜你,荣获班级之星!') # else: # print('不好意思,你的分数是{},缺勤{}次...
#-*-coding:utf-8-*- #@Time :2019/2/25 16:44 #@Author:xiaoqi #@File :task_01.py #1:写一个类 类的作用是完成Excel数据的读写 新建表单的操作 # 函数一:读取指定表单的数据, # 有一个列表row_list,把每一行的每一个单元格的数据存到row_list里面去。 # 每一行都有 一个单独的row_list [[1,2,3],[4,5,6]] #每一行数据读取完毕后,把row_list存到大列表all_row_list # 函数二:在指定的单元格写入指定的数据,并保存到当前Excel # 函数三:新建一个Excel from open...
#-*-coding:utf-8-*- #@Time :2019/2/15 14:09 #@Author:xiaoqi #@File :add_function.py def add(a,b): '''完成a+b的操作,并返回a+b''' return a+b def add_2(*args): sum=0 for item in args: sum+=item return sum def add_5_position_fun(a,b,c,d,e): print(a+b+c+d+e) if __name__=='__main__': #程序执行的入口...
from abc import ABC,abstractclassmethod class Animal(ABC): def __init__(self, name): self.name = name @abstractclassmethod def eat(self): pass class Dog(Animal): def eat(self): print('Meat') class Sheep(Animal): def eat(self): print('Hay') dog = Dog('Mack') cat = S...
from tkinter import * win = Tk() button1 = Button(win, text="Start", fg="blue",bg="yellow").pack(ipadx=5,ipady=5,padx="10cm",pady="30px") button2 = Button(win, text="Start", fg="blue",bg="gray").pack(side="right") win.mainloop()
from tkinter import * from tkinter import filedialog from tkinter.scrolledtext import ScrolledText win = Tk() win.geometry("500x500") def open_file(): file = tkFileDialog.askopenfile(parent=win , mode="r",title="select my file") data=file.read() s.insert(INSERT,data) file.close() def save_file()...
class Student(): """docstring for Student""" def __init__(self, name,family,grade,number): self.name = name self.family = family self.grade = grade self.number = number def showInfo(self): print(f'{self.name} {self.family} information -- > number: {self.number}, grad...
# This is a module which might be helpful in class definition import turtle # function to draw a square shape def draw_square(): window = turtle.Screen() window.bgcolor("white") brad = turtle.Turtle() # brad is an instance of the class Turtle brad.shape("turtle") brad.speed(2) temp1=0 ...
# 什么是Generator 通过next,是一个迭代器 # 怎么用 import memory_profiler as mem # 内存监控 import time nums=[1,2,3,4,5,6] # squre_nums=[n**2 for n in nums] squre_nums=(n**2 for n in nums) # 把[]换成()就是Generator print(next(squre_nums)) # for 本质上就是不断的调用next print(next(squre_nums)) # for 本质上就是不断的调用next print(next(squre_nums)) # for 本质上就是不断的调用...
""" Question: 1.1 Description: Implement an algorithm to determine if a string has all unique characters. """ def is_unique(in_string): """ Uses a dictionary to track which characters have already been seen. Then, If a character is found that is already in the dictionary, the string is not unique. ...
import sys def fib(n, k): if n == 1: return 1 elif n == 2: return 1 else: return fib(n-1, k) + k*fib(n-2, k) print fib(int(sys.argv[1]), int(sys.argv[2]))
#Today we will be converting temperatures def func(): name = input("Please enter your name: ") print("Hello " + name.capitalize()) W = input("what temperature are you converting from: ") if W == "celsius": b = input("what temperature do you want to convert to: ") if b == "fahrenheit": ...
''' class Solution: def minArray(self, numbers: List[int]) -> int: def recursive(left, right): #if numbers[left] < numbers[right]: # return numbers[left] #elif left + 1 == right: if left + 1 == right: return numbers[right] else: ...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains functions and classes related with Maya API maths """ from __future__ import print_function, division, absolute_import import maya.cmds import maya.api.OpenMaya from tpDcc.dccs.maya import api def magnitude(vector=(0, 0, 0)): """ Retu...
import sqlite3 from sqlite3 import Error class WeatherSQLlite: def __init__(self, db_file): self.db_file = db_file self.table_created = False self.conn = None def __del__(self): self.terminate_connection() def create_schema(self, columns_name_type): ...
'''CategoryPickingBehavior module''' # pylint: disable = R0903 import random from PairPickingBehavior import PairPickingBehavior class CategoryPickingBehavior(PairPickingBehavior): '''CategoryPickingBehavior class. Picks a pair according to the first two categories.''' def pick_pair(self, words_in_each_categor...
#!/usr/bin/env python import sys def iterative_factorial(n): product = 1 for i in range(2,n+1): product *= i return product print iterative_factorial(int(sys.argv[1]))
days = { 'senin': 'monday', 'selasa': 'tuesday', 'rabu': 'wednesday', 'kamis': 'thursday', 'jumat': 'friday', 'sabtu': 'saturday', 'ahad': 'sunday' } day = input('Input hari: ').lower() for ind, eng in days.items(): if day == eng: print(f'Bahasa Indonesia dari {day.upper()} adalah {ind.uppe...
# 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 # 示例 1: # 输入: "abcabcbb" # 输出: 3 # 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 # 示例 2: # 输入: "bbbbb" # 输出: 1 # 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 # 示例 3: # 输入: "pwwkew" # 输出: 3 # 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 # 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。 class Solution(object): '''def leng...
import time from datetime import date from datetime import datetime from datetime import timedelta import locale locale.setlocale(locale.LC_ALL, 'ru_RU') print(date.today()) print(datetime.now()) timer = datetime.now() + timedelta(seconds=1.0001) print('time now - ', '\t', datetime.now()) print('time + 1 sec', '\t', t...
#https://pythontutor.ru/lessons/inout_and_arithmetic_operations/ # t=int(input()) # # chas = t//60 # min = t-(chas*60) # print(chas//24) # print(min) t=int(input()) chas = t//60 min = t-(chas*60) print(chas) print(min)
# -*- coding: utf-8 -*- """ Created on Wed Nov 20 09:31:53 2019 @author: Hadeel Fleifel """ #exercise 1 numberOne=int(input("Enter First Number :")) numberTwo=int(input("Enter Second Number :")) if numberOne>numberTwo : print(numberOne,"is Greater than ",numberTwo) else: print(numberTwo,"is Grea...
# -*- coding: utf-8 -*- """ Created on Tue Nov 19 12:21:54 2019 @author: Hadeel Fleifel """ # exercise 1 print('Hello\n \t Hello \n \t \t Hello') #----------------------------------------------- # exercise 2 print("Orange Academy \n"*20 ) #----------------------------------------------- # exercis...
#importer le module argv from sys import argv #definir le module argv qui va avoir deux value a unpack script, filename = argv #on met dans une variable txt l'ouverture du fichier choisi au moment du unpack txt = open(filename) # on affiche le nom du fichier ouvert print "Here's your file %r:" % filename # on affic...
import cx_Oracle import os def db(username,password,ipaddress,serviceid_or_serviceName): os.environ['PATH'] = 'SOME PATH FROM ENVIRONMENT' con = cx_Oracle.connect(username,password,ipaddress,serviceid_or_serviceName) cur = con.cursor() insert_new_record = "insert into TableName values (102,'someStrin...
import numpy as np import pandas as pd import matplotlib.pyplot as plt # ================================================================================== # Load and process results # ================================================================================== # Read and process results from iterative grid refi...
# Given an array of integers, find if the array contains any duplicates. # Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. class Solution: def containsDuplicate(self, nums: List[int]) -> bool: # create a hashtable...
from util import get_valid_coords, Point """ Finds the best placement for each station via brute force. This will iterate over every possible X & Y placement of each station (where stations sharing the same coordinates as a destination or another station is invalid). The time-complexity of this is exponential. ...
def intToBraile(number): one = 10241 # "⠁" beginning of braile in unicode goes to 10495 oldT = number braile = "" while (True): newT = int(oldT/255) r = oldT - (255*newT) if (r == 0 and newT == 0): break else: braile += chr(one+r) oldT = newT return braile if (braile != "")...
komali_school_name = "Johny Mc Donald" ritesh_age = 12 print("komali_school_name -",type(komali_school_name)) print("ritesh_age", type(ritesh_age)) yesh_age = 12 print("Inital yesh_age - ",yesh_age) print("Inital yesh_age type - ",type(yesh_age)) yesh_age = str(yesh_age) print("Post conversion yesh_age - ",ye...
# 18 > = Adult # 5-17 = Child # >0 - 5 = Infant your_age = int(input("Enter you age : ")) if your_age >= 18 : print("ADULT") elif your_age > 5 : print("CHILD") else : print("INFANT")
#Variable is a containers holding some content akshar_age = 10 print("akshar_age : " , akshar_age ) #On re assigning any new value variable looses old value akshar_age = 15 print("On assigning new vaue, akshar_age : ", akshar_age )
import urllib.parse import requests url = "https://codeforces.com/api/user.info?handles=" while True: handle = input("Enter your handle?(Type q to exit) ") if handle == "q" or handle == "quit": break data = requests.get(url+handle).json() if data['status'] == "OK": x = data[...
import math def level_order(tree_list): n = int(math.log(((len(tree_list)-1)/2)+1,2))+1 result = [] end = 0 for i in range(n): start = end end = 2*((2**i)-1)+1 result.append(tree_list[start:end]) return result tree_list = [3,9,20,'#','#',15,7,'#'...
''' Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter the values in the nodes, only nodes itself may be changed. Only constant memory is allowe...
''' Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has one item, it is sorted by definition (the base case). If the list has more than one item, we split the list and recursively invoke a merge sort on both halves. Once the two halves are sorted, the fundamental ope...
''' Given an array of integers, return the highest product possible by multiplying 3 numbers from the array ''' class Solution: # @param A : list of integers # @return an integer def maxp3(self, A): if len(A) < 3: return 0 A = sorted(A) p = A[-1]*A[-2]*A[-3] ...
''' Given a binary tree, flatten it to a linked list in-place. Example : Given 1 / \ 2 5 / \ \ 3 4 6 1 \ 2 \ 3 \ 4 \ 5 \ 6 ''' class Node: def __init__(self,key): self.key =...
''' Given a singly linked list, write a function which takes in the first node in a singly linked list and returns a boolean indicating if the linked list contains a "cycle". A cycle is when a node's next point actually points back to a previous node in the list. This is also sometimes known as a circularly linked list...
import math from typing import Tuple import numpy as np from proj2_code import fundamental_matrix, two_view_data from proj2_code.least_squares_fundamental_matrix import solve_F def calculate_num_ransac_iterations(prob_success: float, sample_size: int, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 18 13:59:40 2019 """ import requests import json import sys apicall = "http://www.omdbapi.com/" def ratings(film, KEY): payload = {'apikey': KEY, 'r': 'json', 't': film} resp = requests.get(apicall, params=payload) if resp.status_cod...
import json """ 概念: 序列化(Serialization): 将对象的状态信息转换为可以存储或可以通过网络传输的过程, 传输的格式可以是JSON,XML等。反序列化就是从存储区域(JSON,XML)读取反序列化对象的状态, 重新创建对象。 JSON(Java Script Object Notation):一种轻量级数据交互格式,相对于XML而言更简单, 也易于阅读和编写,机器也方便解析和生成,Json是JavaScript中的一个子集。 encoding:把一个python对象编码转换成Json字符串 decoding:把json格式字符串编码转换成python对象 具体应用: json提供四个功能:dump...
# 2a) Faça um Programa que converta metros para números # metros = int(input('Insira os metros a serem convertidos em centímetros: ')) # centimetros = metros * 100 # print(centimetros , 'centimetros') # 2b) Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever: F - Feminino, M -...
# mad lib game name = input('what is your name\n ') age = int(input('what is your age\n ')) town = input('what is your home town\n ') color = input('what is your favorite color\n ') status = input('what is your relationship status\n ') print(f'my name is {name}. i am {age} years old. my home town is {town} and my fa...
#!/usr/bin/python ## Name: Vivek Babu G R ## Date: 09-09-2018 ## Assignment: Linked List ## Question 3. Modify Q1 such that one can add a new element after any specified element. ################################################################################################# import user_ds as uds class AddAfterList(u...
def add(number1,number2): return number1+number2 def subtract(number1,number2): return number1-number2 def multiply(number1,number2): return number1*number2 def divide(number1,number2): return number1/number2 if __name__ == "__main__": number1 = int(input("Enter a number: \n")) ...
#!/usr/bin/python3 """ Module for command interpreter """ import cmd 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 import models from mode...
from price import price import unittest class TestPrice(unittest.TestCase): def test_no_book(self): basket = [] self.assertEqual(0, price(basket)) def test_any_single_copy_of_a_book_should_cost_8_euros(self): baskets = ( ["0000000001"], ["0000000002"], ...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ all_path = [] ...
""" Given an array of integers, find the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. """ class Solution(object): def two_sum_sorted_array(self, nums, target): """ :type nums: List[int] :type target: int ...
class Solution(object): def find_the_difference(self, s, t): """ Find the difference between two strings :type s: str :type t: str :rtype: str """ # NOTE:since the other word 't' is shuffled version of 's' # NOTE:we should iterate both strings, count t...
""" Description: Write a program to find the node at which the intersection of two singly linked lists begins. Example: For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8. NOTE: In this example, assume nodes with the same value are the exact same node objects. Do this in...
class Solution(object): def uniquePaths(self, col, row): """ :type m: int :type n: int :rtype: int """ # first create 2d array, 1st row and col equal to 1 dp = [[1 for j in range(col)] for i in range(row)] for i in range(1, row): for j in ...
class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ pascal = [[1]] for row in range(1, numRows): arr = [1]*(row+1) pascal.append(arr) for i in range(1, row): pasca...
""" Description: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. NOTE: An empty string is also consi...
from collections import Counter class Solution(object): def frequency_sort(self, s): """ :type s: str :rtype: str """ if not s: return "" s_counter = Counter(s) # then sort the counter counter_sort = sorted(s_counter.items(), key=lambda x...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ prev = None curr = head ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ pow...
class Solution(object): def getMaximumGold(self, grid): """ :type grid: List[List[int]] :rtype: int """ # early check if not grid or len(grid) == 0: return 0 global_max = 0 visited = [[False for j in range(len(grid[0]))] for i ...
""" Given a set of distinct integers, nums, return all possible subsets AKA: (the power set). Note: The solution set must not contain duplicate subsets. complexity analysis O(n2^n) for oth space and runtime Example: Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] """ ...
# Example Python Program for contrast stretching from PIL import Image # Method to process the red band of the image def normalizeRed(intensity): iI = intensity minI = 86 maxI = 230 minO = 0 maxO = 255 iO = (iI - minI) * (((maxO - minO) / (maxI - minI)) + minO) return iO # Method...
import pandas as pd def create_frame_b(): """This function will create dataframe b Returns: df: dataframe b """ d = {"col1": [1, 8], "col2": [7, 6]} df = pd.DataFrame(data=d) return df
list_name = ["Huma" , "Hina" , "Alina" , "Serat"] print("Hello "+str(list_name[0])+" You are invited to a Dinner") print("Hello "+str(list_name[1])+" You are invited to a Dinner") print("Hello "+str(list_name[2])+" You are invited to a Dinner") print("Hello "+str(list_name[3])+" You are invited to a Dinner")
myStr = "Hello Darkness My Old Friend" #print(dir(myStr)) print(myStr.upper()) print(myStr.lower()) print(myStr.swapcase()) print(myStr.capitalize()) print(myStr.replace('hello', 'bye')) #you can put functions inside other functions, or string them print(myStr.replace('hello', 'bye').upper()) #Numero de caracteres...
#nombre la variable, depues dale el valor con un = name = "Fernando" print(1+2) print(name) name = "NotFernando" print(name) x = 100 book = "Haharry Popotter" Book = "Variables are Case Sensitive" #Las variable no pueden empezar con un numero print(x, book, Book) x, book = 200, "PPOPOPOPOPOP" print(x, book, Book) ...
import tkinter import tkinter.messagebox #--------------------------------------------------------------------------- class form1: def add(self): while True: if self.textbox1=="": self.tkinter.messagebox.showinfo("","** Fields are mandatory") break ...
i=1 n=int(input("enter the number of stars ")) ans="" for i in range(1,n+1): ans=ans+"*" print (ans) i=i+1
""" Module handle file operations """ import re from question import Question class FileReader: """ Class to perform file operations """ file_format = None def __init__(self): self.file_format = '^\d+[\.]\s.*'; @staticmethod def read_file(file_path): """ Read key...
""" in_degree_distribution """ EX_GRAPH0 = {0: set([1, 2]), 1: set([]), 2: set([])} EX_GRAPH1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5: set([2]), 6: set([])} EX_GRAPH2 = {0: s...
import time import argparse def do_work_fn(x, i): return (x >> 2) | (i & x) def inline_loop(x, its): for i in range(its): # 9500000 x = x | (x >> 2) | (i & x) return x def fn_call_loop(x, its): for i in range(its): # 500000): x = x | do_work_fn(x, i) return x def main(): pars...
import hashlib from typing import Any, List class HashableList(list): """ A child class of the built-in list class that is hashable, making it suitable for use as a key in a dictionary. This class overrides the various methods that modify the list so that they set the _hash attribute to None after modific...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import csv, sys import pyperclip LETTERS_TABLE = "table.csv" # def load_letters(csv_file = LETTERS_TABLE): letters = {} # with open(csv_file, mode='r', encoding='utf-8') as file: reader = csv.reader(file, delimiter=';') letters = {row[0]: row[1] ...
import tkinter as t from functools import partial window=t.Tk(className="calculator") window.geometry("1000x600") label=t.Label(text="MY CALCULATOR",font="Helvetica 25 bold",bg="black",relief="sunken",bd=10,fg="white") label.pack(fill="x") var=t.StringVar() def onclick(x): length=len(var.get()) if x=="C": ...
import json import yaml import csv def file_to_raw(filename): with open(filename, "r") as file: f = file.read() return f def dump_to_json(data, filename): with open(filename, "w", encoding="utf8") as file: json.dump(data, file, ensure_ascii=False) def read_csv(filename): rows =...
''' Pedagogical example realization of seq2seq recurrent neural networks, using TensorFlow and TFLearn. ''' from __future__ import division, print_function import os import sys import tflearn import argparse import json import numpy as np import tensorflow as tf from pattern import SequencePattern from tensorflow....
import numpy as np import pdb from scipy.special import expit def sigmoid(z): #SIGMOID Compute sigmoid function # g = SIGMOID(z) computes the sigmoid of z. # You need to return the following variables correctly g = np.zeros(len(z)); # ====================== YOUR CODE HERE ====================== # Instructi...
menu = """ Bienvenido al conversor de divisas 💰 [1] Pesos colombianos [2] Pesos argentinos [3] Pesos mexicanos Elige una opcion: """ def conversion(tipo_pesos, valor): pesos = float(input('Pesos ' + tipo_pesos + ' a convertir: ')) dolar = valor dolares = str(round(pesos / dolar, 2)) print('Tienes ...
def has_numbers(word): return any(char.isdigit() for char in word) def pig_latin(word): """Returns a simplified Pig Latin version of received word""" if has_numbers(word): print("Pig Latin doesn't work numbers, sorry") elif word[0] in ('e','a','i','o','u'): print("{}way".format(word)) ...
def solve(s): result = s[0].capitalize() for x in range(1, len(s)): if s[x-1] == " ": letter = s[x].capitalize() else: letter = s[x] result += letter return result
import os print("RENAME HELPS CHANGE SAME NAMES OR EXTENSIONS OF MULTIPLE FILES AT ONCE") while True: print("TYPE 'Y' TO MOVE TO THE NEXT FOLDER OR 'N' TO STOP AT THAT FOLDER") rootPath = "C:/Users" os.chdir(rootPath) print(rootPath) do = input("Do you want to go further: ").upper() wh...
temp=float(input()) sec=input() if (temp >= 37) and (temp <= 41) and (sec == "S"): print("Exames Especiais") elif (temp >= 37) and (sec == "N"): print("Exames Basicos") elif (temp < 37) and (sec == "N"): print("Liberado") elif (temp < 37) and (sec == "S"): print("Exames Basicos") else: pr...
nota1=int(input()) nota2=int(input()) nota3=int(input()) media=((nota1+nota2+nota3)/3) if (media >= 40) and (media <= 70): print("A media do aluno foi","%.2f"%media,"e ele foi FINAL") elif (media >= 0) and (media <= 40): print("A media do aluno foi","%.2f"%media,"e ele foi REPROVADO") elif (media >= 70)...
forma=input() if (forma == "Q"): ladoq=float(input()) areaq=(ladoq**2) peri=(ladoq*4) print("%.2f"%areaq) print("%.2f"%peri) elif (forma == "R"): largura=float(input()) altura=float(input()) arear=(largura*altura) perir=(2*altura)+(2*largura) print("%.2f"%arear) ...
salario=float(input()) horas=int(input()) if (salario >= 1000.00) and (salario <= 10000.00) and (horas >= 0) and (horas <= 50): horas1=salario/44 salario1=(salario+(horas*horas1)*1.1) print("%.2f"%salario1)
lista = [] n = int(input()) if 1 > n > 1000: print("Erro") else: valor = input().split(" ") for i in valor: lista.append(int(i)) menor_numero = min(lista) a = lista.index(menor_numero) print("Menor valor:",menor_numero) print("Posicao:",a)
import time class UserMessages: SLEEP_DURATION = 3 def __init__(self, printer): self.printer = printer def logo(self): logo = """ ________________ _________ ______ __________ ______ /_ __/ _/ ____/ /_ __/ | / ____/ /_ __/ __ \\/ ____/ / / / // / / / / /|...
#!/usr/bin/env python ''' Programa - AD1.1Q1 Se o número for ímpar * atribui o número ao raio * a partir do raio realiza o cálculo e exibe: * área * perímetro Senão * exibir todos os valores divisíveis do número ''' import math def circulo(rai...
from time import time # recursive binary search def recbinsearch(list,lower,upper,target): if lower <= upper: middle = lower + upper // 2 if target == list[middle]: return False elif target < list[middle]: return recbinsearch(list,lower,middle-1,target) el...
# Multiple Linear Regression (Backward selection model) #import library import pandas as pa import matplotlib.pyplot as plt import numpy as nm # import the dataset dataSet = pa.read_csv('50_Startups.csv') x = dataSet.iloc[:, :-1].values y = dataSet.iloc[:, 4].values # Encode categorical data from sklear...
import webbrowser url = 'https://epaper.eenadu.net' print("-"*10,url,'-'*10,'\n') #Print '-' 10 times URL '-'10 times browser_selection =int(input(" In which browser you want to see? \n\n 1 Google Chrome \n 2 Internet Explorer \n 3 Mozilla Firefox ")) #Take Browser Selction input from user googlechrome=browser...
a_list = [1, 3, 4, 39, 5, 6, 10, 19] def look_for_number(a_list, target_number): l = len(a_list) i = 0 while i < l: if a_list[i] == target_number: return "Found" i += 1 return "Not Found" # results = look_for_number(a_list, 10) # print(results) # employee = { # "name":...
# filename = "some_folder/demofile.txt" # # with open(filename) as the_file: # contents = the_file.read() # print(contents) # filename = "programming.txt" # with open(filename, "w") as the_file: # the_file.write("programming is fun\n") # the_file.write("hello python") def count_words(filename): w...
class MinHeap(object): def __init__(self, elem = [], size = float("Inf")): self.elem = [] self.num = len(self.elem) self.limit = size def isEmpty(self): if self.num>0: return False return True def heapify_up(self, index): parent = index/2...
#do not import any libraries for this question """ Write a function that takes a list of integers as input and returns the sum of the even numbers in the list minus the sum of the odd numbers in the list. The list may contain zeros and negative numbers. For example, f([0, -4, 2, -3, 6, -1, 8, 6]) should return 22. You...
# Importing required libraries import numpy as np from datetime import datetime import matplotlib.pylab as plt # Creating 1D, 2D and 3D arrays # One-Dimensional Array one_dim_array = np.random.randint(12, size=7) # Two-Dimensional Array two_dim_array = np.array([["Cupcake","Donut"], ["Eclai...
import fractions print(fractions.Fraction(2.5)) print(fractions.Fraction(1.2)) arr = [1, 2, 3, 4, 5, 6, 7] for idx, item in enumerate(arr): print('idx:' + str(idx) + ', item:' + str(item))
import turtle from Point import Point from Board import create_board from DFS import tour if __name__ == "__main__": wn = turtle.Screen() board = turtle.Turtle() create_board(board) knight = turtle.Turtle() knight.shape("turtle") knight.penup() knight.speed(1) #knight.goto(-224,224) ...
import re import numpy as np import collections def read(): return [line for line in open("day21.txt")] def get_foods_by_allergen(): foods_by_allergen = {} for line in read(): foods_string, allergene_string = line.strip().split(" (") foods = set(foods_string.split(" ")) for all...
from random import randint input1 = input("Would you like to roll a dice? (y/n)") state = True while state: x = randint(1, 6) if input1.lower() == "y": state = True print("The number is: " + str(x)) input1 = input("Would you like to roll again?") else: print("bye!") ...