text
stringlengths
5
121k
""" Created on Jul 26 @author: Abysswalker """ from math import factorial print(sum(int(digit) for digit in str(factorial(100))))
""" Created on Sat Mar 24 @author: Abysswalker """ from os import path def primeFile(): filepath = path.join(path.dirname(__file__),"primes.txt") primes=set() print("Checking existance of generated prime file") if not path.exists(filepath): raise ValueError("File does not exist, error...") ...
from PIL import Image i = Image.open("input.png") pixels = i.load() width, height = i.size j=Image.new(i.mode,i.size) for image_width_iterator in range(width): for image_height_iterator in range(height): cpixel = pixels[image_width_iterator, image_height_iterator] gray = cpixel[2] ...
from PIL import Image i = Image.open("input.png") pixels = i.load() width, height = i.size j=Image.new(i.mode,i.size) for x in range(width): for y in range(height): cpixel = pixels[x, y] invertedRed = 255 - cpixel[0] invertedGreen = 255 - cpixel[1] invertedBlue ...
class TreeNode: def __init__(self,x): self.val=x self.left=None self.right=None class newTree: def __init__(self,x): self.head=self.new(None,x,0) self.pre,self.mid,self.post=[],[],[] self.pre2,self.mid2,self.post2=[],[],[] self.ceng=[] def...
x = [] y = None print(not x is None) print(not y is None) print(not x) print(not y) print(x is None) print(y is None) print(y == None) x = 1 y = [0] print(not x) print(not y) print(x is None) print(y is None) print(y == None) x = 0 y = [1] print(not x is None) print(not y is None) print(not x) print(not y) print(x is N...
import time def timer(func): def deco(): start_time=time.time() func() end_time = time.time() print("run time%s"%(end_time-start_time)) return deco @timer def test1(): time.sleep(2) print("in the test1") def test2(): time.sleep(2) print("in the test2") test1() ...
f = open("yesterday",'r',encoding="UTF-8") for line in f: if "肆意的快乐" in line: print('s') line=line.replace("肆意的快乐","s") print(line) f.close() line="肆意的快乐" print(line.replace("肆意的快乐","s")) s=line.replace print(line) with open("yesterday","r",encoding="UTF-8") as f: for line in f: ...
class People(object): def __init__(self,name,age): self.name = name self.age = age self.friends = [] print("Run in People") def eat(self): print("%s is eating...."%self.name) def talk(self): print("%s is talking...." % self.name) def sleep(self): ...
def func(self): print('hello %s'% self.name) def __init__(self,name,age): self.name = name self.age = age Foo = type('Foo',(object,),{'talk':func,'__init__':__init__}) f = Foo('Chrn',22) f.talk() print(type(Foo))
import datetime date_in = int(input("Input date : ")) month_in = int(input("Input Month : ")) year_in = int(input("Input year : ")) year = datetime.datetime.now().year print ("You're "+ str(year-int(year_in))+" old") print("Enter to exit")
''' Created on 2016年4月27日 @author: Administrator ''' from tkinter import * class Application(Frame): def __init__(self,master=None): Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.helloLabel = Label(self, t...
name = 'Alabi' print(name) sentence = '''This is a sentense and the sentences continues from here. ''' print(sentence) a = 'Hello, World' print(a[0]) print(a[2:5]) print(a[-5:-2]) print(len(a)) print(a.strip()) print(a.lower()) print(a.upper()) print(a.replace('H', 'J')) print(a.split(',')) pr...
import json import requests class Douban(object): def __init__(self): self.start_url = "https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=20&page_start={}" self.url = [] self.headers = { "User-Agent"...
def combine(array,text): string = "" while len(list(array)) > 0: string += str(array.pop(0)) if len(list(array)) > 0: string += text return string
from benchmark import benchmark def square_root(n, precision): if n < 0: raise 'No sqrt for negative numbers' if n == 0: return 0 log_10 = -1 m = n while n > 0: log_10 += 1 n //= 10 exponent = 2 * (precision - log_10 // 2 ) - 2 return int_sqrt(m * 10**exponent) def int_sqrt...
from math import sqrt def is_prime(n): if n < 2: return False for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True def nth_prime(n): count = 2 i = 3 while count < n: i+=2 if is_prime(i): count += 1 print(i) nth_prime(...
from math import factorial n = factorial(100) digit_sum = 0 while n > 0: digit_sum += n % 10 n //= 10 print(digit_sum)
from primesandfactors import is_prime def run(): primes = {} def primetest(n): if n in primes: return primes[n] else: primes[n] = is_prime(n) return primes[n] def is_truncatable_prime(n): power = 1 while n % 10**power != n: if...
import random import tkinter colors = ['Red', 'Green', 'Blue', 'Yellow', 'Black', 'White', 'Pink', 'Brown'] points = 0 time = 30 def start(e): if time == 30: timer() nextColor() def nextColor(): global time global points if time > 0: e.focus_set() if e....
'''class Solution(object): def subdomainVisits(self, cpdomains): """ :type cpdomains: List[str] :rtype: List[str] """ d={} for i in cpdomains: #print i li=i.split() #print li for b in li[1].split('.'): #print b d[b]=d.get(b,0)+int...
""" This module contains functions used for plotting. """ import numpy as np import matplotlib.pyplot as plt def plot_performance(iteration_number, figures_of_merit): """ Plot the figures of merit This plots the num_parents number of best figures of merit Parameters ---------- iter...
"""Functions using only python. Note: All functions are supposed to work out of the box without any dependencies, i.e. do not depend on each other. """ def element_list_to_value(elem_list, replace_dict): """ Translate list of atoms as string to a list of values according to a dictionary. T...
""" Created on Thu Nov 16 19:47:50 2017 @author: lfoul """ import pygame import math class Emoticon: def __init__(self, sensor) : self.sensor = sensor def setEmoticonParameters(self, size) : self.eyeWidth = 0.1*size self.eyeHeight = 0.15*size ...
""" Created on Thu Nov 16 19:47:50 2017 @author: lfoul """ import pygame from Q3GeneralConfiguration import GeneralConfiguration class Button: def __init__(self, sensor) : self.sensor = sensor def getPosition(self): return [self.sensor.generalConf...
import sqlite3 try: db_connect = sqlite3.connect('C:\sqlite\database\Egor_test.db') sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, email text NOT NULL U...
greeting = "Hello" Greeting = "World" _NAME = "Thiago" Thiago34 = "What" t123 = "Wonderful" print(greeting + ' ' + _NAME) print(Greeting + ' ' + Thiago34 + ' ' + t123) a = 12 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) for i in range(1, a//b): print(i) print(a + b / 3 -4 * 12) ...
parrot = "Hello Everybody" print(parrot) print(parrot[0]) print(parrot[3]) print(parrot[0:2]) print(parrot[:4]) print(parrot[6:]) print(parrot[-1]) print(parrot[0:6:3]) number = "9,234,444,244,039,550,900,857" print(number[1::4]) numbers = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10" print(numbers[0::3])
""" Example code to read in the driving_task data from the REST API server @author: kolim https://www.nylas.com/blog/use-python-requests-module-rest-apis/ import request Also has section on authentication using access tokens Oauth https://www.dataquest.io/blog/python-api-tutorial/ """ import requests import jso...
"""Exercise 3. Split the dataset based on the given ratio. """ import numpy as np def split_data(x, y, ratio, seed=1): """ split the dataset based on the split ratio. If ratio is 0.8 you will have 80% of your data set dedicated to training and the rest dedicated to testing """ np.ra...
speed = int(input('Введите скорость движения, км/ч. ')) time = int(input('Введите время движения, ч. ')) circle_length = 109 if speed > 0: number_of_circle = (speed*time)/circle_length stop_point = round(circle_length * (number_of_circle - int(number_of_circle))) else: number_of_circle = (speed*time)/c...
def TotalCount(M, N, P, Q): count=0 for l in range(M, N + 1): for b in range(P, Q + 1): count+=CountPerChocolateBar(l, b) return count def CountPerChocolateBar(l, b): count=0 while True: longer=max(l, b) shorter=min(l, b) count+=1 diff=longer - ...
def plusMinus(arr): print(arr) len_arr=len(arr) print("length::",len_arr) tot_pos=0 tot_neg=0 tot_zeros=0 print(sum((tot_pos+1,tot_neg+1) for i in range(len(arr)) if arr[i]>0 for j in range(len(arr)) if arr[j]<0 )) if __name__=="__main__": arr=[-4,3,-9,0,4,1] plusMinus(arr)
pv = 10000*(1+0.03) print(pv/0.03) id(pv) str1 = 'Just' str2 = 'in' str3 = str1 + str2 print(str3) Wight = 72 print('請輸入身高') Hight = int(input()) x = Hight/100 BMI = Wight/(x*x) type(BMI) a = [50, 20, 60, 40, 30] print('a: ', a) a.sort() print('排序後的結果 a: ', a) ...
donors = {"Timothy Tander": [100, 200, 300], "Tara Towers": [200, 400, 600], "Charlie Day": [700, 100, 2000], "Sandra Connors": [1800, 2300, 7000], "Betsy Hammond": [500, 190, 212, 55]} donors["Timothy Tander"].append(800) def thank_you(full_name, donation): print("\n D...
print('Enter PP length in cm:') pplength = float(input()) print('Enter PP thickness:') ppthickness = float(input()) ppvolume = ppthickness/2**2*3.14*pplength print('your pp is %s cm3'%ppvolume) if ppvolume > 23: print('U Hav Beeg PP') elif ppvolume < 19: print('U Hav Smol PP') else: print('U Hav Normie PP')
import random base_num = raw_input('Please input a number: ') def get_guess(base_num, repeat): if (repeat == True): return raw_input('Wrong! Guess again: ') else: return raw_input('Please guess a number between 0 and ' + base_num + '. ') if (base_num == ''): print('Please provide a num...
import math import numpy as np from scipy.integrate import solve_ivp h_array = [] error_array = [] period = 24. * 3600. earth_mass = 5.97e24 earth_radius = 6.378e6 gravitational_constant = 6.67e-11 total_time = 9. * 3600. marker_time = 0.25 * 3600. initial_radius = earth_radius + 200*1000 in...
def kalimat(x): if len(x)>200: print('Batas Karakter Maksimal Hanya 200') elif len(x)==0: print('Masukkan Sebuah Inputan') else: text = '*{}*' print(text.format(x.upper().replace(' ',''))) x= input('Masukkan Sebuah Kalimat : ') kalimat(x)
print ("The How Much You Need to Retire Calculator") monthly_spend = int(input("How much money in terms of today's money will you need on retirement (per month)? £")) ir = int(input("What return from investments you can achieve in the long term? %")) inflation = int(input("What average real inflation should I includ...
ch=input("") if((ch>='a' and ch<='z') or (ch>='A' and ch<='Z')): if(ch=='a',ch=='e',ch=='i',ch=='o',ch=='u',ch=='A',ch=='E',ch=='I',ch=='O',ch=='U'): print("Vowel") else: print("Constant") else: print("invalid")
""" Fibonacci dynamic programming - top-down (memoization) approach Using Python's 'memo' decorator Other ways to implement memoization in Python: see Mastering Object-Oriented Python, p. 150 (lru_cache) """ def fibonacci(n): return fib(n, {}) def fib(n, memo= {}): if n == 0 or n == 1: re...
import math def merge(list1, p, q, r): len_lhs = q - p + 1 len_rhs = r - q len_sum = len_lhs + len_rhs lhs_new = list(list1[p : q+1]) rhs_new = list(list1[q+1:r+1]) lhs_new.append(math.inf) rhs_new.append(math.inf) cursor_lhs = 0 cursor_rhs = 0 for i in ra...
with open("Input/Names/invited_names.txt") as file: name_list = [] names = file.readlines()
def simps(f,a,b,N=50): '''Approximate the integral of f(x) from a to b by Simpson's rule. Simpson's rule approximates the integral int_a^b f(x) dx by the sum: (dx/3) um_{k=1}^{N/2} (f(x_{2i-2} + 4f(x_{2i-1}) + f(x_{2i})) where x_i = a + i*dx and dx = (b - a)/N. Parameters --------...
import csv import yaml from pprint import pprint with open("lesson-2/data-read.csv", "r") as file: reader = csv.reader(file) headers = next(reader) data = dict(zip(headers, reader)) pprint(data) with open("lesson-2/data-from-csv.yaml", "w") as file: yaml.dump(data, file)
import unittest def min_range(listeners, towers): largest = 0 t1 = towers[0] i = 0 for listener in listeners: d1 = abs(listener - t1) if d1 <= largest: continue if i + 1 < len(towers): t2 = towers[i + 1] d2 = abs(t2 - listener) if...
""" Stock Prices Greedy algorithm You are given access to yesterday's stock prices for a single stock. The data is in the form of an array with the stock price in 30 minute intervals from 9:30 a.m EST opening to 4:00 p.m EST closing time. With this data, write a function that returns the maximum profit obtainable. ...
""" Coin Change You are given coins of different denominations and a total amount of money. Write a function to compute the fewest coins needed to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. As an example: Input: coins = [1, 2, 3], amount = 6 O...
def sieve(n): """to find all the prime numbers up to a specified maximum""" sieve_list = [] if n in range(2,65536): for p in range(2,n): sieve_list.append(p) else: print("E...
import scipy.io import numpy as np from matplotlib import use use('TkAgg') import matplotlib.pyplot as plt from oneVsAll import oneVsAll from predictOneVsAll import predictOneVsAll from displayData import displayData from predict import predict np.set_printoptions(threshold=np.inf) print('Exercise 1:...
if __name__ == '__main__': print("Hello there!! \nThis code to practise some basics in python. \n ") str = "Hello world" print(str[2:]) print("Enter an integer greater then zero and less or equal 100 ") n = int(input().strip()) if (n % 2) != 0: print("We...
from itertools import permutations if __name__ == '__main__': word=list(map(str,input().split(" "))) len = int(word[1]) per=permutations(list(word[0]),len) arr=sorted(per) for x in arr: strr=x[0]+x[1] print(strr)
class Wheel(): def __init__(self, maker, size): self.maker = maker self.size = size def wheel_description(self): print("This wheel is " + str(self.size) + " maked by " + self.maker) class Car(): '''模拟汽车的简单尝试''' def __init__(self, make, model, year, maker, si...
from itertools import count, cycle for el in count(10): if el > 20: break else: print(el) n = 0 for el in cycle('Hello'): if n > 9: break print(el) n += 1
""" Created on Tue Oct 8 03:36:08 2019 @author: Ellis_Pax """ question = { '1':"What is your favourite snack?", '2':"What is your favourite 2019 movie?", '3':"What is your fvourite holiday resort?", '4':"Who do y...
""" Test cases """ from unittest import TestCase from Calculator import add from Calculator import multiply from notes import get def add_note(strings,string): strings.append(string) return strings class NotesTestCase(TestCase): """ Notes Test""" def test_get_note_from_list(self): """ get n...
num = int(input("Enter an integer greater than 1. ")) factorlist = [] print() while (num > 1): i=2 while (i <= num**(.5)): if num%i != 0: i = i+1 else: factorlist = factorlist + [i] num = int(num/i) i = 2 factorlist = factorlist + [num] num = 1 primelist = [] explist = [] for facto...
from turtle import Screen, Turtle class ScreenGenerator: def __init__(self): self.generate_screen() self.generate_line() def generate_screen(self): screen = Screen() screen.setup(width=1000, height=600) screen.bgcolor("black") screen.title("My Pong Game") ...
import pandas as pd df=pd.read_csv("DataTable.csv") pos_dict={"C":[],"W":[],"D":[],"G":[]} for index, item in df.iterrows(): if item["DKPos"] in pos_dict: pos_dict[item["DKPos"]].append({"DKSalary":item["DKSalary"],"FDFP":item["FDFP"],"PlayerID":item["PlayerID"]}) for pos,item in pos_di...
""" Escribir un programa los cuadrados de los 60 primeros numero naturales, usar bucle while y for """ print("*****Bucle While*****") i = 0 while i <= 60: print(f"EL cuadrado de {i} es: {i * i}") i += 1 else: print("Programa terminado con bucle while!!") print("______________________________") print("*****Bucle ...
import unittest from markovchain import MarkovChain class TestMarkovChain(unittest.TestCase): """Tests the public methods for the MarkovChain class.""" def setUp(self): self._corpus = "This is a, sample' corpus.\n How neat is that.\n" self._expected_chain = {'this': {'is': 1}, ...
def two_unique(num): arr = [] for i in range(len(num)): temp = num[i] num.pop(i) if temp not in num: arr.append(temp) num.append(temp) return arr print(two_unique([5, 5, 2, 4, 4, 4, 9, 9, 9, 1]))
from keras.datasets import cifar10 from keras.utils.np_utils import to_categorical from keras.models import Sequential, Model from keras.layers import Dense, LSTM, Conv2D from keras.layers import Flatten, MaxPooling2D, Dropout import matplotlib.pyplot as plt (x_train, y_train),(x_test, y_test) = cifar10.load_...
from logical_prop import LogicProposition, gen_table, get_max_width, print_table from sys import stdout, stdin p = None if stdout.isatty() and stdin.isatty(): print(" ! is the symbol for not\n","| is the symbol for or\n","& is the symbol for and\n","> is the symbol for implies\n","= is the symbol for if and only if...
from math import sqrt, degrees,atan class Point(object): ''' classdocs ''' def __init__(self, x,y): ''' Constructor ''' self.id=0 self.x=x+0.0 self.y=y+0.0 self.isOnVertex=False def getAngle(self,vertex): a...
''' Created on Feb 5, 2016 @author: sharvani ''' import SquarePosition class TreeNode(object): def setPosition(self, x, y): self.position = SquarePosition.SquarePosition() self.position.setPosition(x, y) def getPosition(self): return self.position def setValue(self, v...
while True: try: year = int(input("Enter a year: ")) except ValueError: print("Input is invalid. Please enter an integer input(year)") continue break if (year%4) != 0: print(str(year) + " is not a leap year.") else: if(year%100) != 0: print(str(year) + " is a leap year.") else: if(year%400) == 0: pr...
""" Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: X-DSPAM-Confidence: 0.8475 Count these lines and extract the floating point values from each of the lines and compute the average of those values """ fname = input("Enter file name: ") ...
''' Created on 02-Jun-2016 @author: BALASUBRAMANIAM ''' data=(5,"Coimbatore",78.5,True) print(data) print(data[1:]) listdata=list(data) listdata.append(56) print(listdata)
''' Created on 03-Nov-2016 @author: BALASUBRAMANIAM ''' data=(4,'keeranatham',True) nestedTuple=(('Ashok',567569756),('Aruna',356995345 ),('Karthik',46704765467)) for tuple in nestedTuple: for data in tuple: print(data,"\t", end='') print() hrData=l...
''' Created on 01-Jun-2016 @author: BALASUBRAMANIAM ''' from _decimal import Decimal import fractions n = 15 print(bin(n)) print(oct(n)) print(hex(n)) print(float(n)) binarydata=bin(n) print(int(binarydata,2)) print(int(hex(n),16)) import fractions x = fractions.Fraction(1, 3) print(x)
def reverse(s): s=s[::-1] print(s) def cee(n): n=n.capitalize() print(n)
import unittest def is_string_unique_char_array(s): """ only support ASCII, use extra array of 128 chars for this version""" char_counts = [0] * 128 if s is None: return False for i in s: i_ord = ord(i) if i_ord > 127: raise ValueError("char %s out of range" % i) char_counts[i_ord] += 1 ...
st = 'Αιγαίο, με βελτίωση του' def allign_text(line, width): sp = ' ' extra_spaces = width- len(line) print(line, extra_spaces) if sp in line: while extra_spaces > 0 : line = line.replace(sp, sp+' ', extra_spaces) print(line) ...
import re tonoi = ('αά', 'εέ', 'ηή', 'ιί', 'οό', 'ύυ', 'ωώ') tw = 'trivizas_works.txt' try: with open(tw, 'r', encoding = 'utf-8') as f: works = f.read() for line in works.split('\n'): print(line) except IOError as e: print(e) while True: phrase = input('Δώσε λέξη-κλειδί:') if ph...
import re with open('vouna.txt', 'r', encoding = 'utf-8') as f: text = f.read() for line in text.split("\n"): line = line.split("\t") oros =line[0] height = int(line[1]) perioxh = line[2] perioxh = re.sub(r'\([^)]*\)', '', perioxh).split(",") ...
def seqCount(n): le = 1 while (n>1): if (n&1): n = 3*n+1 else: n = n//2 le += 1 return le maxN = 1 maxL = 1 m = 1000000 for i in range (1, m): le = seqCount(i) if (maxL < le): maxL = le maxN = i print(maxN)
''' Extended Euclidean Algorithm ---------------------------- This algorithm determined the greatest common divisor (GCD) of two integers (​numbers). Also, It returns two integers such that GCD(a, b) = xa + by. @author: @alanveloso ''' def gcd(a, b): ''' Run extended euclidean algorithm. Parameters ---...
def nthFibonacii(n): if n == 1: return 0 if n == 1 or n == 2: return 1 return nthFibonacii(n-1) + nthFibonacii(n-2) dp = {} def memFibonacci(n): if n == 1 or n == 2: return n-1 if n not in dp: dp[n] = memFibonacci(n-1) + memFibonacci(n-2) return dp[n] def ...
def max_ways_to_reach_staircase_end(staircase_height, max_step, current_step=1): if staircase_height == 0 or current_step == 0: return 1 elif staircase_height >= current_step: return max_ways_to_reach_staircase_end( staircase_height-current_step, max_step, current_step-1) + stairc...
from cs50 import get_int def main(): hashCount = 2 while True: height = get_int("Height: ") if height >= 0 and height <= 23: break spaceCount = height - 1 for i in range(height): for j in reversed(range(spaceCount)): print(" ", end="") for j in re...
import re text_1 = "This is some text, that can be used. I am not sure! How many characters? This is an extra line " text_2 = "What the hell ?" text_3 = "whoopwhoop." text_4 = "This is crazyyyyy " text_5 = "This is some kind of a test. Yeaah." def remove_extra_lines(text): list_of_suffix = [".", ",", "!", "?"] ...
day, month, year = 0, 0, 0 myday = int(input()) year = myday/365 myday = myday % 365 month = myday/30 myday = myday % 30 day = myday if month >= 12: aa = month/12 year+=aa month %= 12 print("%d ano(s)\n%d mes(es)\n%d dia(s)\n" % (year, month, day))
x = float(input()) y = float(input()) if x == 0 and y == 0 : print("Origem\n") elif x > 0 and y > 0: print("Q1") elif x < 0 and y > 0: print("Q2") elif x < 0 and y < 0: print("Q3") elif x > 0 and y < 0: print("Q4") elif x == 0: print("Eixo X") elif y == 0: print("Eixo Y") print("")
salario = float(input()) imposto_1 = 0 imposto_2 = 0 imposto_3 = 0 if salario <= 2000: print("Isento") else: if 4500 < salario: imposto_3 = (salario - 4500) * 0.28 salario = salario - (salario - 4500) if 3000 < salario: imposto_2 = (salario - 3000) * 0.18 salario = salario - ...
N, M, P = map(int, input().split()) palavras = [] for i in range(0, N): palavras.append(input()) linha = [] matriz = [] for i in range(0, M): linhas = input() for char in linhas: linha.append(char) matriz.append(linha[:]) linha.clear() PRINCIPAL = [] ACIMA = [] ABAIXO = [] DIAGONAL = [] CO...
x = int(input()) y = int(input()) soma = 0 for n in range(y+1, x): if n % 2 != 0: soma = soma + n print(soma)
def what_are_n(): storage = [] container = 0 while container != -1: container = int(input("Enter a number in which you would like to find multiples of: ")) if container == -1: break if type(container) is int and container not in storage: storage.append(container) ...
""" The factorial of the integer n, written n!, is defined as: n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1 Calculate and print the factorial of a given integer. Complete the extraLongFactorials function in the editor below. It should print the result and return. extraLongFactorials has ...
def binary_search(arr, search_el): if len(arr) > 0: mid = len(arr) // 2 mid_el = arr[mid] if mid_el == search_el: return mid elif search_el > mid_el: return binary_search(arr[:mid], search_el) elif search_el < mid_el: return binary_search(a...
dict1 = {'1': 'a', '2': 'b', '3': 'c'} print(dict1) print(dict1['2']) empty = {} print(type(empty)) dict((('F', 70), ('i', 105))) dict(one=1, two=2, three=3) dict2 = {} dict2 = dict2.fromkeys((1, 2, 3), ('one', 'two', 'three')) print(dict2) dict3 = {} dict3 = dict3.fromkeys(range(10), 'good') print(dict3.keys...
from abc import ABCMeta, abstractmethod class Employee(object, metaclass=ABCMeta): def __init__(self, name): self._name = name @property def name(self): return self._name @abstractmethod def get_salary(self): pass class Manager(Employee): def get_salary(self): return 15000.0 class Pr...
qa = int(input("Quantidade de elementos: ")) k = int(input("valor da soma: ")) lista = [] for r in range(qa): a = int(input("elemento:")) lista.append(a) i = len(lista) - 1 for e in lista: if(lista[i] + e == k): print("sim") break else: print("nao") break i-=1
age = 22 if age >= 18: print("Adult") elif age >= 13: print("Teenager") else: print("Child") print("done") if age > 1: pass else: pass name = "baidwan" if not name: print("Not a name") age = 22 if age >= 18 and age < 60: print("Eligible") if 18 <= age < 60: print("eligible"...
import re s = 'Alex:1994,Sunny:1993' pattern = r"(\w+):(\d+)" l = re.findall(pattern, s) print(l) regex = re.compile(pattern) l = regex.findall(s) print(l) re.split(r':|,', s) print(l) s = re.subn(r'\s+','#','This is a test',2) print(s) s = re.sub(r'\s+','#','This is a test',2) print(s)
import matplotlib.pyplot as plt m = 50 g = 9.81 c = 10 V_current = 0 T_current = 0 T_list = list() V_list = list() for i in range(1,10): T_new = i T_list.append(T_new) print(T_new) V_new = V_current + (g-(c*V_current/m))*(T_new - T_current) V_list.append(V_new) print(V_new) T_current = T_new V_current = V...
Functions={1:"Numbers",2:"List",3:"Sets",4:"Strings",5:"Tuples",6:"Dictionaries"} for values,keys in Functions.items(): print(values,keys) Func_input=int(input("Enter the function to be performed from above options:")) def Number_Operations(): Number_ops={1:"Add",2:"Subtract",3:"Multiply",4:"...
'''a=[2,5,4,8,9,3] #reversing list a.reverse() print(a)''' '''a=[1,3,5,7,9] #deleting element from list del a[1] print(a)''' '''a=[6,0,4,1] #clearing all elements from list a.clear() print(a)''' '''n = [1, 2, 3, 4, 5] #mean l = len(n) nsum = sum(n) mean = nsum / l print("mean is",mean)''' '''n=[...
""" Created on Thu Mar 22 13:32:37 2018 @author: lasiand """ import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X ...