text
stringlengths
5
121k
import config board = [ [" ", "|", " ", "|", " "], ["-", "+", "-", "+", "-"], [" ", "|", " ", "|", " "], ["-", "+", "-", "+", "-"], [" ", "|", " ", "|", " "], ] def print_board(): for line in board: for char in line: print(char, end="") print() def reset_board...
'''This is python progaramm where i am doing swapping of two number using two approches. 1. with hardcorded values 2. Values taken from user also in this i have added how to use temporary variable as well as without delcaring temporary varibale. ============================================================ ''' impo...
from Tweet import * from Ronronear import * class Main(): ronronear = Ronronear() usuario = "@"+input("Ingrese su usuario: ") print("Bienvenido/a "+usuario+"\n") while (True): try: op = int(input("1. Add tweet\n2. Cambiar de usuario\n3. Ver usuarios - tweets\n4. Salir\n")) if(op==4): break els...
def introuduction(): Name=input('What is your Name') print('How are you doing?,'+Name+'') Candy=input('What Candy do you like?') print('Nice! I like '+Candy+' too!') Cheese=input('What kind of Cheese do you like best?') print('I could eat '+Cheese+' all the time!') print('sorry I have to go ...
import turtle turtle.speed(0) turtle.shape('turtle') turtle.left(90) i = 0 while i < 4: n = 0 while n < 180: turtle.forward(1) turtle.right(1) n = n + 1 n = 1 while n < 180: turtle.forward(0.15) turtle.right(1) n = n + 1 i = i + 1 input()
import turtle as t n = int(input('Введите количество лап' + '\n')) t.shape("turtle") t.color("blue") t.width(2) for i in range(n): t.forward(80) t.stamp() t.backward(80) t.left(180) t.left(180 * (n - 2) // n) input()
import sys import random def rock_paper_scissors(n): global all_combinations all_combinations = [] move_options = ['rock', 'paper', 'scissors'] def build_moves(countdown, piece_being_built): if countdown == 0: all_combinations.append(piece_being_built) return ...
class RingBuffer: def __init__(self, capacity): self.capacity = capacity self.current = 0 self.storage = [None]*capacity def append(self, item): self.storage[self.current] = item if self.current == len(self.storage)-1: self.current = 0 else: ...
""" Created on Mon May 4 12:40:06 2020 @author: TakahiroKurokawa """ def FizzBuzz(): for i in range(1,101): if (i%3==0) & (i%5==0): print("FizzBuzz") elif i%3==0: print("Fizz") elif i%5==0: print("Buzz") else: print(i) a=FizzBuzz(...
""" Created on Sat May 2 14:49:56 2020 @author: TakahiroKurokawa """ class Shape: def __init__(self): pass def what_am_i(self): return "I am a shape" class Square(Shape): square_list=[] def __init__(self,l): self.name="Square" self.l=l self.square_list.append...
def findelement(arr, n,key): for i in range (n): if (arr[i])==key: return i+1 else: continue arr = [1,2,4,2,3,1,5,6,3,1] n = len(arr) print(findelement(arr, n , 5))
""" vc pode dar loop em dicionarios de 3 formas: loop nas keys: loop nos values: loop nos key , values: """ favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in favorite_languages.keys(): print(name.title()) for languages in f...
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero.") print("\n-------------------------------------------------------") print("\nGive me 2 numbers, and i'll divide them:") print("Enter 'q' to quit.\n") while True: first_number = input("Enter the first number> ") if first_n...
def greet_users(names): for name in names: msg = f"hello {name.title()}, you wellcome" print(msg) user_names = ['apk','shiit','crep','big mak'] greet_users(user_names) modelos_nao_finalizados = ['a','b','c','d','e'] modelos_finalizados = [] while modelos_nao_finalizados: modelo_feito = model...
class Restaurant: def __init__(self,restaurant_name,cuisine_type): self.name = restaurant_name self.cuisine = cuisine_type self.number_served = 0 def describe_restaurant(self): print(f"Restaurant name: {self.name}") print(f"Restaurant cuisine type: {self.cuisine}") ...
import pygame from window import * from snake import * from apple import * pygame.font.init() def showYouLost(window): font = pygame.font.SysFont("comicsans", 60) text = font.render("You lost", 1, (255, 255, 255)) window.blit(text, (420, 200)) def main(): window = Window(900, 900) w...
""" // Time Complexity :T = O(M) + O(N) // Space Complexity :O(n) // Did this code successfully run on Leetcode : YES // Any problem you faced while coding this : NA add all the pattern characters in hashmap with default value 1 in character -> reduce its count in hashmap; if the cout is 0, incr...
def modulo(numero,modulo): risultato = numero % modulo return risultato while 1: num=input("dammi il numero :") num=int(num) mod=input("dammi il modulo :") mod=int(mod) ris=modulo(num,mod) print("viene "+str(ris))
import re filename = 'regex_sum_1136998.txt' filetxt = open(filename) regex = '[0-9]+' sumInts = 0 countInts = 0 integers = [] newIntList = [] newIntItemStr = '' for line in filetxt : line = line.rstrip() integers.append(re.findall(regex, line)) onlyInts = [listItems for listItems in integers if listI...
import re filename = input("Enter file: ") fhand = open(filename, 'r') nums = [] for line in fhand: match = re.search("group\s(\d+)", line) if match: nums.append(int(match.group(1))) print(sum(nums)/len(nums)) print(sum(nums))
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) email_count = {} for line in handle: line = line.rstrip() words = line.split() if len(words) == 0: continue if words[0] == "From": email_count[words[1]] = email_count.get(words[1], 0) + 1 max_c...
def computepay(hours, rate): pay = hrs * rate if hours > 40: overtime = (hours - 40.0) * (0.5 * rate) pay += overtime return pay if __name__ == '__main__': hrs = float(input("Enter Hours: ")) rate = float(input("Enter Rate: ")) p = computepay(hrs, rate) print("...
def productExceptSelf(nums): numsLength = len(nums) leftProducts, rightProducts = [0]*numsLength, [0]*numsLength leftProducts[0] = 1 for i in range(1, numsLength): leftProducts[i] = nums[i-1] * leftProducts[i-1] rightProducts[numsLength - 1] = 1 for i in reversed(range(numsLen...
ord = int(input("숫자 입력: ")) crd = ( (str(ord) + "st") if (abs(ord) % 10 == 1 and abs(ord) % 100 != 11) else (str(ord) + "nd") if (abs(ord) % 10 == 2 and abs(ord) % 100 != 12) else (str(ord) + "rd") if (abs(ord) % 10 == 3 and abs(ord) % 100 != 13) else str(ord) + "th" ) print(crd)
import random play = input('would you like to roll dies: ').strip().lower() if play == 'yes': rolls = int(input("Enter number of dies to roll: ")) def diesRoll(rolls): for i in range(0, rolls): dies = random.randint(1, 6) print(dies) diesRoll(rolls) else: exit() ...
email = input() while True: cmd = input() if cmd == "Complete": break elif "Make Upper" in cmd: email = email.upper() print(email) elif "Make Lower" in cmd: email = email.lower() print(email) elif "GetDomain" in cmd: count = int(cmd.split...
from datetime import datetime, timedelta from hashlib import md5 import pytz import sys class utcTime: def __init__(self,sInput): self.input = [int(i) for i in sInput.split(' ')] self.utc = datetime(self.input[0],self.input[1],self.input[2],self.input[3],self.input[4],...
import sys from binascii import unhexlify, hexlify import argparse parser = argparse.ArgumentParser(prog='xor.py',conflict_handler="resolve") parser.add_argument("text",metavar="text",nargs="+",help="Add name of text file") parser.add_argument("key",metavar="key",nargs="+",help="Add name of key ...
import random RollDice=input('Do you want to roll the dice:') RollDice = RollDice.upper() while(RollDice == 'YES'): print(random.randint(1,6)) RollDice=input('Do you want to roll the dice again:') RollDice = RollDice.upper()
import math from math import gcd def my_gcd(a, b): ''' returns: str gcd for two given numbers ''' if a == b or b == 0: return a elif a > b: return gcd(a-b, b) else: return gcd(b-a, a) def lcm(a, b): '''''' return a * b // gcd(a, b) def get_prime_factors...
from myutil import is_prime, get_next_prime def largest_prime_factor(n): if n <= 2: raise(RuntimeError('number should be greater than 2')) else: factor = get_next_prime(1) while True: if is_prime(n): return (n) if n % factor == 0: ...
with open('testinputMatches2-bin.txt') as f: for line in f.readlines(): line = line.strip() if line and not line[0] == "#": print("{} ==> {}".format(line, int(line, 2))) else: print(line)
import sys import math sys.setrecursionlimit(1200) def test(x): print("test function") return def printNumbers(num): if (num == 0 ): return 0 if (num == 1000): print("onethousand "+str(len("onethousand"))) return len("onethousand")+printNumbers(num-1) hundred = 0 ten...
""" Created on Wed Apr 13 @author: Xiang Li IDE: Spyder Python 3.4 """ from data_structures import Stack def revstring(mystr): """ :type mystr: string :rtype: string use Stack Last In First Out feature to reverse a string """ aStack = Stack() for i in list(mystr): aStack.pus...
""" Created on Mon Sep 28 14:04:06 2015 @author: Shawn Li IDE: Spyder python 3.4 """ def findAlphabetSub(s): '''Find longest alphabet substrings Argus: String: string with all lower cases Return: String: substring ''' charList = list(s) alphabetSubMax = [] i = 0...
def hex_to_dec(s): return int(s, 16)
import unittest from collections import Counter def input_file(): file = open('input', 'r') lines = [line.rstrip('\n') for line in file] file.close() return lines def output_file(): file = open('output', 'r') res = [line.rstrip('\n') for line in file] file.close() return res def fi...
""" 3-. El Mono Infinito, parte 2: generador de frases Alemany Ibor, Sergio Galindo Jiménez, Carlos Santiago """ import sys import pickle import random def load_object(file_name): with open(file_name, 'rb') as fh: obj = pickle.load(fh) return obj def generate_sentence(file_name): aux = load_o...
user_prompt = True while user_prompt: age = input ("What is your age? ") if age.isdigit() and int(age) < 120: user_prompt = False print(f"Your age is {age}!") else: print("Please provide your answer in digits")
print("What is your name?") name = input() print("Hi") print(name) print("What is your DOB?") DOB = input() print("Wow you are born on the,") print(DOB) print(type(DOB))
import random from abc import ABC, abstractmethod PlayerPositions = ["Goalkeeper", "Defender", "Midfielder", "Attacker"] class Players(ABC): @abstractmethod def __init__(self, fname, lname, value, position, score): self.id = 0 self.first_name = fname self.last_name = lname se...
def write_to_file(file, order_item): try: with open(file, "w") as file: file.write(order_item + "\n") except FileNotFoundError: print(f"The file {file} does not exist!") write_to_file("writing_orders.txt", "banana")
from s_Teams import Teams import random class Match: def __init__(self, team1: Teams, team2: Teams): self.team1 = team1 self.team2 = team2 self.winner = None def play_match(self): if self.team1.team_score + random.randint(-5, 5) > self.team2.team_score + random.rand...
import random from abc import ABC, abstractmethod class Players(ABC): @abstractmethod def __init__(self, fname, lname, value, position, score): self.__first_name = fname self.__last_name = lname self.__value = value self.__position = position self.__score = score ...
import re from collections import Counter def main(): str = '1223999404427' print("you gave me", str) numRegex = re.compile(r'(\d)\1*') num = numRegex.findall(str) c = Counter(re.findall(r'\d',str)) print(c) if __name__=="__main__": main()
import pandas import timeit def main(): print("find of a factorial of n: n!") n = 6 timeit print("fctorial of {} is {}".format(n,factorial(n))) def factorial(n): if n == 1 or n == 0: return 1 return n * factorial(n-1) if __name__=="__main__": main()
import operator def main(): print('Let us see how to sort in dictionaries') dict1 = {'aa':1, 'pp':4, 'cc':2, 'tt':3} print('this is our dict1=', dict1) sorted_dict1 = sorted(dict1.items(), key=operator.itemgetter(1)) print('after sorting it acc to values=',sorted_dict1) sorted_dict2 = sorted(di...
def main(): list = [2,5,0,6,7] print("sorted numbers=",insertionSort(list)) def insertionSort(numbers): for i in range(0,len(numbers)): current = numbers[i] j = i-1 while numbers[j] > current and j>=0: numbers[j+1] = numbers[j] j=j-1 numbe...
from tkinter import * root = Tk() root.title('100 Days Of Python - Day 6') root.configure(background='#B3E5FC') frame = LabelFrame(root, text=' FizzBuzz ', bg='#B3E5FC', fg='#1A237E', font=15, padx=75, pady=75) frame.pack(padx=20, pady=20) info = Label(frame, text='Enter a number:', bg='#B3E5FC', font=.5) info.g...
print('Welcome to iPython Supermarket') bill = float(input('How much is your bill? ... ')) tax = bill*(15/100) print(f'TAX is 15%\nBill is {bill}') print(f'~~~~~~~~~~~~\nThe total including the TAX is {bill+tax}$') print('THANK YOU, SEE YOU AGAIN ^-^')
import openpyxl wb = openpyxl.load_workbook('produceSales.xlsx') sheet = wb.get_sheet_by_name('Sheet') PRICE_UPDATES = { 'Garlic': 3.07, 'Celery': 1.19, 'Lemon': 1.27 } for rowNum in range(2, sheet.max_row): produceName = sheet.cell(row=rowNum, column=1).value if produceName in PRICE_UPDATES:...
grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O'...
def commaList(listValue): counter = 0 newString = '' while counter < len(listValue)-1: newString += str(listValue[counter]) + ', ' counter += 1 print(newString + 'and ' + str(listValue[counter])) return newString + 'and ' + str(listValue[counter]) spamList = ['ap...
def displayInventory(inventory): print("Inventory:") item_total = 0 for k, v in inventory.items(): print(v, k) item_total += v print("Total number of items: " + str(item_total)) def addToInventory(inventory, addedItems): for i in range(len(a...
import re def pwStrength(pw): if eightChars.search(pw) and oneUpper.search(pw) and oneLower.search(pw) and oneDigit.search(pw) != None: print('Your password meets the requirements.') else: print('Your password does not meet the requirements.') eightChars = re.compile(r'.{8,...
import random, logging, traceback logging.basicConfig(level = logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') logging.disable(logging.CRITICAL) logging.debug('Start of program') def guess(): guess = '' while guess != 'heads' and guess != 'tails' and guess != 'h' and guess ...
''' Created on Apr 6, 2011 @author: aaron ''' def solve(): ''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ''' num = 600851475143 while (num % 2 == 0): num /= 2 for i in range(3,600851475143,2): ...
from csv import DictReader employee_info = [] with open("employees.csv", newline="") as f: reader = DictReader(f) for row in reader: row["age"] = int(row["age"]) row["salary"] = float(row["salary"]) employee_info.append(row)
import turtle import random as rd class L_systemDrawer(): '''Provide ways to build a L-system and draw it with a turtle''' def __init__(self, instructions='F-G-G', iterations=5, distance=10, angle=120): self.t = turtle.Turtle() self.wn = turtle.Screen() self.instructions = instructions...
class sum_maximum: def __init__(self): self.array_input() def array_input(self): length = int(input("Enter the number of elements: ")) input_array = [] for i in range(0, length): input_array.append(int(input("Enter element into array: "))) print("Input arra...
class rearrange_positive_negative_alternatively: def __init__(self): self.array_input() def array_input(self): length = int(input("Enter number of elements in the array: ")) input_array = [] for i in range(length): input_array.append(int(input("Enter element into a...
import re def check_ranges(ranges,data): if ":" in ranges: ranges=dict([x.split(":") for x in ranges.split(",")])[re.search("(\D+)",data).group()] num=int(re.search("(\d+)",data).group()) (min,max)=ranges.split("-") return int(min)<=num<=int(max) def check_rule(rs,rule,data): ...
import time a = time.time() print(a) c = time.localtime() print(c) d = time.gmtime() print(d) print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) print(time.strptime("2021-01-19 15:12:44", "%Y-%m-%d %H:%M:%S")) print(time.mktime(time.localtime())) aa = time.strptime("1998-08-09 00:00:...
print(sum([i for i in range(1, 101)])) print((lambda i: sum(i))(i for i in range(1, 101))) print(sum(range(1, 101)))
a = [1, [1, 2, 3], 1.23, 'abc'] b = a.copy() b[1] = a[1].copy() print(id(a[1])) print(id(b[1])) print(id(a)) print(id(b)) ''' 浅复制:对于可变类型没有完全复制 深复制:全部复制 '''
s = '*' for i in range(1, 8, 2): print((s * i).center(7)) for i in range(5, 0, -2): print((s * i).center(7))
""" 列表(list,数组):以中括号为边界,以逗号隔开的数据(各种类型) 特点: 1,有序的 2,可变的 3,支持索引 4,支持切片 """ a = [1, True, None, [1, 2, 3], 'abc', (1, 2, 3), {'a': 1}, {1, 2, 3}, 1.23] for i in a: print(f'{type(i)}-->{i}') print(a[3]) print(a[::-1])
a = 0 b = 0 for i in range(2, 101): for j in range(2, i): if i % j == 0: a = 1 if a == 0: b += i else: a = 0 print('for_100以内所有质数的和为', b) print('-' * 100) a = b = 0 i = 1 while i < 100: i += 1 j = 2 while j < i: if i % j == 0: ...
""" 写入文件 """ """ 读 """ count = 0 a = open('a.txt', 'r', encoding='utf-8') for i in a.readlines(): if i.startswith('#') or i == '\n': count += 1 print(count) a.close() count = 0 a = open('a.txt', 'r', encoding='utf-8') b = a.readlines() for i i...
i = 0 while i < 5: i += 1 if i == 3: break print("hello world") else: print("输出五次了") print("*"*20) i = 0 while i < 5: i += 1 if i == 3: continue print("hello world") else: print("输出五次了")
i = 0 count = 1 while count <= 100: i += count count += 1 print(i) i = 0 count = 1 while count <= 100: if count % 2 == 0: i += count count += 1 print(i) i = 0 count = 2 while count <= 100: i += count count += 2 print(i)
""" 类属性 """ """ 类方法 """ class A(): name = 'A' def __init__(self): self.age = 23 def printInfo(self): print(A.name) @classmethod def a(cls): print(cls.name) print('类方法') a = A() a.a() A.a() b = A() b.a()
class House(): def __init__(self, addr, area): self.addr = addr self.area = area self.free = self.area self.funcList = [] def __str__(self): result = f"当前位置:{self.addr}\n" result += f"总面积:{self.area}平方米\n" result += f"剩余面积:{self.free}平方米\n" ...
def odwrocZdanie1(x): y = x.split() result = [] for word in y: result.insert(0, word) return " ".join(result) def odwrocZdanie2(x): y = x.split() return " ".join(y[::-1]) def odwrocZdanie3(x): y = x.split() return " ".join(reversed(y)) def odwrocZdanie...
"""Class representing the a single square in the crossword grid.""" from dataclasses import dataclass from typing import Optional @dataclass class Square: is_black: bool = False letter: Optional[str] = None index: Optional[int] = None starts_down_word: bool = False starts_across_word: bool = False...
class Solution: ''' It is said that it is better not to use recursion in python. By default Only 1000 times recursion is allowed sys.setrecursionlimit(10000) ''' def findMedianSortedArrays(self, A, B): m=len(A) n=len(B) if (m+n)%2==1: return float(self.fi...
import tkinter import tkinter.messagebox root = tkinter.Tk() def display_and_print(): tkinter.messagebox.showinfo("Info","Just so you know") tkinter.messagebox.showwarning("Warning","Better be careful") tkinter.messagebox.showerror("Error","Something went wrong") okcancel = tkinter.messageb...
class Chain(object): def __init__(self, path = ''): self._path = path def __getattr__(self, path): return Chain('%s/%s' % (self._path, path)) def __call__(self, path = ''): return Chain('%s/%s' % (self._path, path)) def __str__(self): return self._path __repr__ = __str__ def main(): print( Chain()....
from functools import reduce class Solution: def sumFourDivisors(self, nums: List[int]) -> int: def factor(n): return set(reduce(list.__add__, [[i, n//i] for i in range(1, int(n**0.5)+1) if not n%i])) total = 0 for num in nums: f = factor(nu...
class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: def dfs(node: TreeNode, l: List) -> bool: if node is None: return if node.left is None and node.right is None: l.append(node.val) return l ...
def recuperer_item(liste, indice): if abs(indice)>=0 and abs(indice)<len(liste): return liste[indice] elif indice < 0 and abs(indice) == len(liste): return liste[indice] else : return "Index {i} hors de la liste".format(i=indice) liste = ["Julien", "Marie", "Pierre"] print(recupere...
a = 4 b = 6 c = 2 ens = {a,b,c} min_1 = min(ens) ens.discard(min_1) min_2 = min(ens) ens.discard(min_2) min_3 = min(ens) print("Les nombres dans l'ordre sont {}, {} et {}".format(min_1, min_2, min_3)) a1 = min(a, b, c) a3 = max(a, b, c) a2 = (a + b + c) - a1 - a3 print("Les nombres dans l'ordre sont {}, {} et {}"...
def checkNumbers(): numbers = [] userNumber = 'x' sumOfNumbers = { 'lessThan': 0, 'biggerThan': 0, 'equalTo': 0 } print('Wpisz liczby do porówniania, jeśli chcesz zakończyć wpisywanie użyj klawisza enter') while(userNumber != ''): userNumber = input('Podaj liczbę...
""" Created on Tue Apr 3 08:01:33 2018 @author: mariana.frasson """ """ Dados n pontos (x,y) para cada ponto, determinar se (x,y) pertence a região H. """ def main1(): n = int(input("Digite n:")) count = 0 while count < n: x = float(input("Digite x:")) y = float(input("Digite y:")) ...
import os import csv filepath = os.path.join("budget_data_1.csv") with open(filepath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") print("Financial Analysis") print("**************************************") total_months = [] for row in csvreader: total_months....
from itertools import permutations from json import dumps def findHappyness(people): print("People:", people) total = len(list(permutations(people, len(people)))) count = 0 best = {"arrangement": None, "happyness": 0} for combo in permutations(people, len(people)): happyness = 0 ...
if __name__ == "__main__": with open("input.txt", "r") as r: data = r.read() r.close() niceCountSetA, niceCountSetB = 0, 0 for name in data.split(): everyTwoLetters = [name[i] + name[i + 1] for i in range(0, len(name) - 1)] vowelCount = True i...
def findPassword(pRange): start, end = pRange.split("-") possibilities = [] for p in range(int(start), int(end)+1): if(len(str(p)) != 6): continue double = False strP = str(p) for i in range(0, 5): if(strP[i] == strP[i+1]): ...
name = input("What is your name?") print('"Hello, Neo :)"')
from tkinter import * window = Tk() window.title("Calculator") window.configure() operator="" text_input=StringVar() num = Entry(window, font="arial 20 normal",width=20, borderwidth=5, textvariable=text_input, bd=30, insertwidth=3, bg="powderblue") num.grid(row=0, column=0, columnspan=3, padx=10, pady=10) def b...
""" 2020年2月17日15:44:53 按照不同的小区进行分类并计算小区总价平均值 使用plt进行数据展示 """ import matplotlib.pyplot as plt import pandas as pd plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False from_path = "..\\doc\\processed_data\\cd_lianjia-v3_ed.csv" to_path = "..\\doc\\pic\\area_mean_pric...
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: head=ListNode(0) ptr=head while head: if l1 is None and l2 is None: break elif l1 is None: ptr.next=l2 break elif l2 is N...
def main(): with open('input.txt') as f_in: for line in f_in.readlines(): print(condense(line.strip())) def condense(sentence): condensed = [] tokens = list(reversed(sentence.split(' '))) while len(tokens) > 1: first, second = tokens.pop(), tokens.pop() similarit...
import time from memory_profiler import profile data = [-1, -2, -1, 1, -2, 3, -1, 2, -3, 2] @profile() def max_1(lt): max_sum = 0 max_list = [] for i in range(len(lt)): for j in range(len(lt) + 1): if lt[i: j] == []: continue ...
def firstMissingPositive(self, nums: List[int]) -> int: i, j = 0, len(nums) while i < j: if nums[i] == i + 1: i += 1 elif nums[i] > 0 and nums[i] <= j and nums[nums[i] - 1] != nums[i]: nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i]...
def twoSum(self, numbers: List[int], target: int) -> List[int]: l, r = 0, len(numbers) - 1 while l < r: if numbers[l] + numbers[r] == target: return [l + 1, r + 1] elif numbers[l] + numbers[r] > target: r -= 1 else: l += 1 return...
def pivotIndex(self, nums: List[int]) -> int: leftSum, rightSum = 0, sum(nums) for i, v in enumerate(nums): rightSum -= v if leftSum == rightSum: return i leftSum += v return -1
class English: def Greeting(self): return "Hello!" def Farewell(self): return "Good byee." class Translator: _English = None _engphrases = { "Hello!": "CZEŚĆ", "Good byee.": "Do widzenia" } ...
import PyPDF2 def extract_text_by_page(pdf_path): pdfFileObj = open(pdf_path, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) print(pdfReader.numPages) for pageNumber in range(0,pdfReader.numPages): pageObj = pdfReader.getPage(pageNumber) ...
def binSearch(arr, first, last, K): if last < first: index = -1 else: mid = int((first+last)/2) if K == arr[mid]: index = mid elif K < arr[mid]: index = binSearch(arr, first, mid-1, K) else: index = binSearch(arr, mid+1, last, K) return index print(binSearch([1,2,3,4,5,6,7,8,9], 0, 8, 6))