text
stringlengths
5
121k
a = "Hello" l = list(a) print(l) j=''.join(l) print(j) j1 = ' '.join(l) print(j1) j2 = '_'.join(l) print(j2)
""" There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have t...
""" You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui,vi,wi) ui is the source node, vi is the target node wi is the time it takes for a signal to travel from source to target We will send a signal from a given node k. Return the...
""" You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assum...
""" 계단을 올라가고 있다. 이 계단의 꼭대기에 도착하려면 n개의 steps만큼 올라가야 한다. 한번 올라갈 때 마다 1step 또는 2steps 올라갈 수 있다. 꼭대기에 도달하는 방법의 갯수는 총 몇가지 일까요? input: n=2 output = 2 1. 1+1 2. 2 input: n=3, output =3 1. 1+1+1 2. 1+2 3. 2+1 DP using topdown memo = {} def dp_topdown(n): if n == 1: return 1 if n == 2: return 2 ...
""" 문제: 정렬되어 있지 않은 정수현 배열 nums가 주어졌다. nums원소를 가지고 만들 수 있는 가장 긴 연속된 수의 갯수는 몇개인지 반환하시오 input: nums =[100,4,200,1,3,2] output: 4 (가장 긴 연속된 수 1,2,3,4) 문제 해결: O(nlogn) method: #1. sort the nums #2. then from beginning consecutive sequence. O(n) method using hash table: #1. 100,4,200,1,3,2 [101:T, 5:T, 201:T, 2:T, 4:T,...
""" **Instruction** Write P4 function that reads a file and creates another file with different delimeter. - Assume the input file is delimited with blank(' '). - Output file has comma(',') as a delimeter - Assume there is no consecutive blanks in input file. i.e. ' ', ' ', ' ',... does not appear in the input f...
""" **Instruction** Please see instruction document. """ from linked_list_helper import ListNode, create_linked_list, print_linked_list def P3(head: ListNode) -> ListNode: if head is None: return None if head.next is None: return head ''' # Find the number of nodes cnt = 0 cu...
""" #Practical programming Chapter 9 Exercise 3 **Instruction** Write a function that uses for loop to add 1 to all the values from input list and return the new list. The input list shouldn’t be modified. Assume each element of input list is always number. Complete P3 function P3([5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, ...
""" **Instruction** Please see instruction document. """ def P2(parentheses: str) -> bool: par_list = ['.'] for i in parentheses: if i == '(' or i == '{' or i == '[': par_list.append(i) elif i == ')': if par_list[-1] == '(': par_list.pop() ...
""" Implement a function that takes a list of integers as its input argument and returns a set of those integers occurring two or more times in the list. >>> P1([1,2,3,1]) {1} >>> P1([1,2,3,4]) set() >>> P1([]) set() >>> P1([1,2,3,1,4,2]) set({1,2}) """ def P1(lst): result = set() noDup = set(lst) ...
from tkinter import * canvas_height = 400 canvas_width = 600 canvas_colour = "black" x_coord = canvas_width/2 y_coord = canvas_height line_colour = "red" line_width = 5 line_length = 5 def move(x, y): global x_coord global y_coord new_x_coord = x_coord + x new_y_coord = y_coord + y ...
from tkinter import * import table, ball, bat, random window = Tk() window.title("MyBreakout") my_table = table.Table(window) x_velocity = 4 y_velocity = 10 first_serve = True my_ball = ball.Ball(table = my_table, x_speed=x_velocity, y_speed=y_velocity, width=24, height=24, colour="red", x_s...
class Solution: def increasingBST(self, root: TreeNode) -> TreeNode: def inOrder(root: TreeNode, vals: List[int]): if root is None: return inOrder(root.left, vals) vals.append(root.val) inOrder(root.right, vals) vals = [] ...
a,b = tuple(int(x) for x in input("").split(" ")) y = 0 while a <= b: a *= 3 b *= 2 y += 1 print(y)
class Velocity(): ''' Velocity for objects ''' def __init__(self,xspeed = 0, yspeed = 0): self.xspeed = xspeed self.yspeed = yspeed class Coord(): ''' Coordinates for objects ''' def __init__(self, xpos, ypos): self.xpos = xpos self.ypos = ypos
""" Helper functions to process directories and files. @author: amagrabi """ import os import shutil import magic def delete_path(path): shutil.rmtree(path) def create_folders(folder_list, path): for folder in folder_list: folder_path = os.path.join(path, folder) if not os.path.exists...
Product = "Pepsi" Quantity = 10 Unit_Price = 1.25 Amount = Quantity * Unit_Price VAT = Amount * 11 / 100 print("Product:", Product) print("Quantity Purchased:", Quantity) print("Unit Price:", Unit_Price) print("----------------------------------") print("Total Bill:", Amount) print("VAT:", VAT) print("Net Amount:", (Am...
names = [] choice = "" longest = "" second = "" print("------------------------------------------") while choice != "exit": choice = input("Enter name (exit to quit):") if choice != "exit": names.append(choice) if len(choice) > len(longest): second = longest longest = cho...
name = input("Enter Name:") salary = int(input("Enter Salary:")) if salary >= 35000: VAT = salary * 21 / 100 if salary < 35000: VAT = salary * 17 / 100 print("----------------------------------------------") print("Name:", name) print("Salary:", salary) print("----------------------------------------------") pr...
name = input("Enter Name:") phy = int(input("Enter Physics Marks:")) che = int(input("Enter Chemistry Marks:")) mat = int(input("Enter Mathematics Marks:")) tot = phy + che + mat per = tot * 100 / 450 print("-------------------------------------") print("Name:", name) print("Total Marks:", tot) print("Percentage:", per...
no = int(input("Enter Number:")) print("-----------------------------------") if no > 1000: print("A") if no > 5000: print("C") else: print("E") else: print("B") if no > 500: print("D") print("-----------------------------------")
def swap_bits(x): return (x & 0b10101010) >> 1 | (x & 0b01010101) << 1
from collections import defaultdict TOP_LEFT_TO_BOTTOM_RIGHT = 0 TOP_RIGHT_TO_BOTTOM_LEFT = 1 def combos(num): return num * (num - 1) / 2 def pairs(bishops, m): counts = defaultdict(int) for r, c in bishops: top_lr, top_lc = (r - min(r, c), c - min(r, c)) top_rr, top_...
def rand7(): r1, r2 = rand5(), rand5() if r2 <= 3: return r1 elif r2 == 4: if r1 <= 3: return 6 else: return rand7() else: if r1 <= 3: return 7 else: return rand7()
def reverse(head): prev, current = None, head while current is not None: tmp = current.next current.next = prev prev = current current = tmp return prev
from random import randrange def process_list(n, l): all_nums_set = set() for i in range(n): all_nums_set.add(i) l_set = set(l) nums_set = all_nums_set - l_set return list(nums_set) def random_number_excluing_list(n, l): nums_list = process_list(n, l) idx = randrange(0, len(nu...
def shifted_array_search(lst, num): i = len(lst) // 2 dist = i // 2 while True: if lst[0] > lst[i] and lst[i - 1] > lst[i]: break elif dist == 0: break elif lst[0] <= lst[i]: i = i + dist elif lst[i - 1] <= lst[i]: ...
import random class Move(object): def __init__(self,car, direction): """Create a new Rush Hour board. Arguments: vehicles: a set of Vehicle objects. """ self.car = car self.direction = direction self.w = random.randint(1,500) de...
''' 739. Daily Temperatures Medium Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. For example, given the list of temperatu...
''' 226. Invert Binary Tree Easy Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the so...
import sqlite3 def create_table(): conn = sqlite3.connect('test.db') conn.execute('''CREATE TABLE IF NOT EXISTS EMPLOYEES (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL);''') print("Table created success...
a = [i for i in range(10)] def get(a): while True: for i in range(0, 10, 3): try: if i+3 < 10: yield a[i:i+3] else : raise Exception except: break; b = get(a) for i in range(20): print(next...
import unittest import csv import re data = [] with open('IMDBmovies.csv', 'r') as file: csv_reader = csv.reader(file) for line in csv_reader: if len(line) != 0: data.append(line) class Testing_Project(unittest.TestCase): def test_if_deposited(self): for movie in self.movie...
import json def convert_json_data(file): """Read in the data from a json file and convert it to a Python object""" with open (file, mode='r') as json_object: data = json_object.read() return json.loads(data) products_json = convert_json_data('products.json') products = products_json['produ...
"""Get user input for product item to search""" def get_item_name_from_user(): """Get a name of a product from the user""" return input("What is the product name? ").title()
Weather = { "city": "Moscow", "temperature": "20" } Weather['temperature'] = int(Weather['temperature']) - 5 print(Weather) print(Weather.get("country")) Weather.get("country", "Russia") Weather["date"] = "27.05.2019" print(len(Weather))
import pandas as pd from pandas.core.indexes.base import Index student = { 'name': ['DJ', 'RJ', 'YP'], 'eno': ['19SOECE13021', '18SOECE11001', '19SOECE11011'], 'email': ['dvaghela001@rku.ac.in', 'xyz@email.com', 'pqr@email.com'], 'year':[2019,2018,2019] } df = pd.DataFrame(student,index=[10,23,13]) p...
import numpy as np ary = np.array([1,2,3,5,8]) ary = ary+1 print(ary[1])
a = 10 b = 9 c = 11 print("Global Variables A =",a,", B =",b,", C =",c) print("ID of var B :",id(b)) def something(): global a a = 15 b = 5 globals()['c'] = 16 x = globals()['b'] print("\nLocal Variables A =",a,", B =",b,", C =",c,", X =",x) print("Inside func the ID of var B :",id(x)) ...
import re search = ''' abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 @#$%^&(*((^&))) 123-456-7896 563-658-7566 456*254&2454 ''' print(r"\tRKU") a=r"\tabc" print(a) pattern = re.compile(r'\d{3}.\d{3}.\d{4}') matched = pattern.finditer(search) for match in matched: print(match) print(se...
import pandas as pd df = pd.read_csv('ETH.csv') filt1 = df['Date'].str.contains('2019') filt2 = df['Date'].str.contains('2020') print("highest value of column 'Open' for the year 2019 : ",df.loc[filt1,'Open'].max()) print("highest value of column 'Open' for the year 2020 : ",df.loc[filt2,'Open'].max())
class student: _name = None _roll = None __college = None myvar = "RKU1" def __init__(self,name,roll,college): self._name = name self._roll = roll self.__college = college @classmethod def change_myvar(cls): cls.myvar = "RK University" print(...
def showNumbers(limit): for i in range(0,limit+1): if(i%2 == 0): print(i,"EVEN") else: print(i,"ODD") limit = int(input("Enter Limit : ")) showNumbers(limit)
import numpy as np ls =[] print("Enter Element in Matrix : ") for i in range(0,9): ls.append(int(input())) def display(ls): array = np.array(ls).reshape(3,3) return array dim = display(ls) print(dim)
def main(): nome = input('') estado_civil = int(input('')) n1 = [] n2 = [] if estado_civil == 2: n1.append(nome) for i in n1: print(len(i)) elif estado_civil == 1: nome2 = input('') n1.append(nome) n2.append(nome2) for i in n1: ...
def media(n1, n2, n3, n4, n5): return(n1+n2+n3+n4+n5) / 5 def main(): n1 = float(input("".strip())) n2 = float(input("".strip())) n3 = float(input("".strip())) n4 = float(input("".strip())) n5 = float(input("".strip())) maior = [] if n1 > media(n1, n2, n3, n4, n5): maior.append...
import sys from interface import BookInterface from additional import Text, GColor PhoneBook = BookInterface() GREEN = GColor.RGB(15, 155, 43) def main_menu(): print(GREEN + Text.BOLD + '*' * 18 + " MAIN MENU " + '*' * 18 + Text.END) print("Please, select an action by choosing its index.\nOperations:") p...
import unittest from DistanceTable import * class TestDistanceTable(unittest.TestCase): def test_not_a_valid_file(self): '''Test to make sure an IOError is raised for an invalid file name''' with self.assertRaises(FileNotFoundError): DistanceTable.readCSV(self, 'does-not-exist.csv') def test_get_a_saved...
while True: a=input('Enter number a:') b=input('Enter number b:') try: result= int(a)/int(b) except ZeroDivisionError: print("Zerro division") except ValueError: print("Not a digit") else: print('Square Resutl:',result**2) break
def solution(nums): ''' Approach: 1. using 3 pointers, slow pointer indicates all values before it are traversed. 2. fast pointer quickly moves to new values and prev=fast and slow moves one step and fast moves to nex and flag=0 3. if flag ==0 then only move make nums[slow]=nums[fast] 4. slow po...
def puntuacion (clase): return sum (clase) / len (clase) clase = [7, 8, 9] media = puntuacion (clase) print ("La puntuacion de esta clase es: ", media) clase = [5, 6, 7.5, 10] media = puntuacion(clase) print ("La puntuacion de esta clase es: ", media)
tienes_llave = input ("Tienes una llave?: ") if tienes_llave == "si": forma = input ("Que forma tiene la llave?: ") color = input ("Que color tiene la llave?: ") if tienes_llave != "si": print ("Si no tienes llaves no entras") if forma == "cuadrada" and color =="roja": print (...
import csv file_name = 'budget_data_1.csv' with open(file_name, newline='') as csvfile: budget_data = csv.reader(csvfile, delimiter=',') next(budget_data) Total_Months = 0 Total_Revenue = 0 Revenue_Change = 0 Total_Revenue_Change = 0 Prev_Month_Revenue = 0 Gretes...
""" 编写一个函数,调用函数返回四位不含0的随机数. """ import random def random_number(figure): num = 0 for i in range(1,figure+1): num = num*10 + random.randint(1,9) return num if __name__ == '__main__': print(random_number(4))
def ubahjumlah(datas2, datas3): ketemu = False while not(ketemu): id_ubah= input("Masukan ID: ") ID = 0 nama = 1 jumlah = 3 if id_ubah[0] == "G" or id_ubah[0] == "C": if id_ubah[0] == "G": for i in range(len(datas2)): ...
op = [5, 1, 2, 3, 4] d = 3 arr = [1,2,3,4,5] def reverse(arr): i = 0 b = len(arr)-1 while i < b: arr[i], arr[b] = arr[b], arr[i] i += 1 b -= 1 return arr def rotate_by_d(arr, d): arr = reverse(arr) ...
arr = [2, 3, 3, 3, 3] l = 0 h = len(arr) search = 3 def binary_search(arr, l, h, search): mid = l+h//2 if search == arr[mid] and (mid == 0 or arr[mid-1] != search): return mid elif search <= arr[mid]: return binary_search(arr, l, mid, search) else: return binary_search(ar...
string = "l" l = 0 r = len(string)-1 def check_palindrom(l, r, string): if string[r] != string[l]: return False if l < r: check_palindrom(l+1, r-1, string) return True print(check_palindrom(l, r, string))
"""Put a monocolor frame around images.""" import click from PIL import Image from ..param import COLOR def frame(image, width, color): """Put a monocolor frame around images.""" frame_pixels = round(width * max(image.size)) new_size = (image.size[0] + 2 * frame_pixels, image.size[1] + 2 * frame_pixels)...
import numpy as np import matplotlib.pyplot as plt F = 600 r0 = 4 r_y = r0 r_x = 0 r_t = r_y - 35 r = np.array([r_x, r0]) r_norm = np.linalg.norm(r) v_x = 7 v_y = -2 v = np.array([v_x, v_y]) mu = 0.0 dt = 0.01 plt.axis([-r_norm, r_norm, -r_norm, r_norm]) def get_g(r, F = F): return -F * np.linalg....
from itertools import product from pprint import pformat import sys def main(): coefficients = [1,4,3,0,1,2] run(*coefficients) def run(*coefficients): for p in [2,3,5]: print(f'\n{p}:\n') results = factor(p, coefficients) for result in results: print(list(result[0]),...
import sys import os """ replaces the spaces in file names by underscores ('_') works with any number of files/folders dragged and dropped on the script""" def newname(path): output = path.split('\\') output[-1] = output[-1].replace(' ', '_') if ' ' in output[-1] else False return '\\'.join(outpu...
from typing import Any, List, Tuple, Union def broken_search(elements: Union[List[Any], Tuple[Any]], target: Any) -> Any: left, right = 0, len(elements) - 1 while left <= right: mid = (left + right) // 2 if target == elements[mid]: return mid if elements[mid] <= elements[ri...
cars = ['bmw','audi','toyota','subaru'] print(len(cars))
number = input("If you input a number ,I will tell you if the number is multiplier of ten! Please input the number: ") number = int(number) if number%10 == 0: print("It`s the multiplier of ten!") else: print("It`s not the multiplier of ten!")
age=40 if age<2: print("He is a baby.") elif 2<=age<4: print("He is a child.") elif 4<=age<13: print("He is a children.") elif 13<=age<20: print("He is a teenager.") elif 20<=age<65: print("He is an adult. ") elif age>65: print("He is an old man")
users=['admin','root','peter','psla','seare'] for user in users: print("Hello "+user+'.') if user=='admin': print("Hello "+user+','"would you like to see a status report?") else: print("Hello Eric,thank you for logging in again")
cities={ 'taizhou':{ 'country':'china', 'population':'1000 million', 'fact':'水乡,好吃的多', }, 'dongjin':{ 'country':'japan', 'population':'20000 million', 'fact':'鬼子多', }, 'new york':{ 'country':'america', 'population':'90000 million', ...
cars = ['bmw','audi','toyota','subaru'] for car in cars: if car =='bmw': print(car.upper()) else: print(car.title())
kaart = int(input('kaart is: ')) totaal = 0 while totaal < 21 and kaart > 0: totaal += kaart if totaal < 21: kaart = int(input('kaart is: ')) if totaal > 21: antw = 'Verbrand ({})'.format(totaal) if totaal == 21: antw = 'Gewonnen!' if kaart == 0: antw = 'Voorzichtig gespeeld ({})'.form...
from math import sqrt a = float(input('Geef x: ')) if a < 2: if x == 2: mes = '{:.2f} ∉ dom(f)'.format(a) else: mes = '' elif x < 2: mes = 'x ∉ dom(f)' print(mes)
URL = 'https://medium.com/' def write_to_file(file_name, url): """This function writes the received url to the received file name.""" with open(file_name, 'a') as myfile: myfile.write('{}\n'.format(url)) def format_internal_url(url): """This function formats an internal path to a valid URL....
import os from collections import Counter def checkMagazine(magazine, note): c = Counter(magazine.split(' ')) for word in note.split(' '): count = c.get(word, 0) if count == 0: return "No" else: c[word] -= 1 return "Yes" if __name__ == '__main__': fpt...
import numpy as np class MovingAverageDoubleStrategy: """ Double moving average strategy. """ def __init__(self, period_1=9, period_2=21, trade_fee=0): if period_1 > period_2: self.period_max = period_1 self.period_min = period_2 else: self.period_max = per...
import pandas as pd import csv import os from pathlib import Path path_run = os.path.dirname(__file__) src_dir_name = '\source_input_files' tgt_file_name = '\processed_output\\Combined.csv' src_input_path= path_run + src_dir_name tgt_output_path = path_run + tgt_file_name def get_process_ip_det...
a=str(input("Enter text to encrypt:")) key=13 enc="" for i in range (len(a)): char=a[i] if(char.isupper()): enc += chr((ord(char) + key-65) % 26 + 65) else: enc += chr((ord(char) + key-97) % 26 + 97) print("Encrypted Text is:") print(enc)
import json from abc import ABC, abstractmethod class LoadDATA(ABC): @abstractmethod def load(self, filename): pass class LoadJSON(LoadDATA): def load(self, filename): with open(filename, 'r') as f: json_data = json.load(f) return json_data
import os import numpy as np szFloat = 8 def findRAM(): txt = os.popen("free -m -b").readlines() freeM = txt[1].split()[3] return int(freeM) def calcNDecomp(nVals): fac = .8 totMem = int(fac*findRAM()) dataMem = nVals*szFloat return 1+dataMem/totMem
import sys def build_suffix_array(text): """ Build suffix array of the string text and return a list result of the same length as the text such that the value result[i] is the index (0-based) in text where the i-th lexicographically smallest suffix of text starts. """ suf...
import sys def get_fibonacci_huge_naive(n, m): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current % m def get_fibonacci_huge(n, m): el_mod_m, i = [0, 1], 2 while not (el_mod_m[i - 2] == 0 ...
from collections import namedtuple from queue import PriorityQueue AssignedJob = namedtuple("AssignedJob", ["started_at", "worker"]) def assign_jobs_naive(n_workers, jobs): result = [] next_free_time = [0] * n_workers for job in jobs: next_worker = min(range(n_workers), key=lambda w: next_...
import sys import random def less_than_or_equal(num1, num2, let1, let2): return less_than(num1, num2, let1, let2) or \ equal(num1, num2, let1, let2) def less_than(num1, num2, let1, let2): return num1 < num2 or \ (num1 == num2 and let1 < let2) def equal(num1, num2, let1, let2): r...
import nltk from nltk.corpus import stopwords from nltk.util import ngrams from nltk.probability import FreqDist from string import punctuation class Ngram: def __init__(self, text): """ Initialize :param text: The string based on which the Ngram instance is created """ self...
fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] print(sorted(fruits, key=lambda word: word[::-1])) print(abs, str, 13) print([callable(obj) for obj in (abs, str, 13)]) import random class BingoCage: def __init__(self, items): self._items = list(items) random.shuffle(s...
s = 'ABC' for char in s: print(char) it = iter(s) while True: try: print(next(it)) except StopIteration: del it break from PythonTest.S14.s14_1 import Sentence s3 = Sentence('Pig and Pepper') it = iter(s3) print(it) print(next(it)) print(next(it)) print(next(it)) try: print(...
import re match_regex = re.compile(r"match\s+\{") else_regex = re.compile(r"\}\s+else\s+\{") name_regex = re.compile(r"""(r"([^"]+)")""") word = re.compile(r"[a-z]+") stat = False output = "" with open('src/simpla.lalrpop') as file: for line in file.readlines(): if match_regex.match(line): ...
from utils.single_link import SingleLinkedList data = [ 4, 5, 6] data=[2, 4, 5, 8] final_result = [] index = 0 while index < len(data): sing = None if index == len(data) - 1: final_result.append(SingleLinkedList(data[index])) elif data[index] + 1 == data[index + 1]: flag = False ...
""" BinaryGap Find longest sequence of zeros in binary representation of an integer. A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001...
import csv import matplotlib.dates from datetime import datetime from matplotlib import pyplot as plt def date_to_list(data_index): """ save date to a list """ results = [] for row in data: results.append(datetime.strptime(row[data_index], '%Y-%m-%d')) return results def data_to_list(data_in...
class Solution: def isValid(self, s: str) -> bool: if len(s)==0: return True valid_char = ['(', ')', '{', '}', '[', ']'] left_half = ['(', '[', '{'] right_half = [')', ']', '}'] ...
def BST_valid(root, min_value, max_value): if not root: return True if (root.val >= max_value) or (root.val <= min_value): return False left_test = BST_valid( root.left, min_value, root.val) right_test = BST_valid( root.right, root.val...
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 == None: return l2 if l2 == None: return l1 dummy_node = ListNode(None) current_pointer= dummy_node ...
class Solution: def evalRPN(self, tokens: List[str]) -> int: my_stack = [] operators = ['+', '-', '*', '/'] for token in tokens: if token not in operators: operand = int(token) ...
import sys import numpy as np from PyQt5.QtWidgets import QApplication, QLabel, QLineEdit, QVBoxLayout class Form(QLabel) : def __init__(self, parent=None) : super(Form, self).__init__(parent) self.function_edit = QLineEdit("f(x) = ...") self.function_edit.selectAll() ...
class FileReader: def __init__(self, path): self.file = open(path, 'r') self.nodes = set() self.edges = [] self.edge_cost = dict() self.parse() """ Data is written in .txt file like: begin_node, end_node, cost, direction; This method parses all ...
''' Created on Mar 27, 2017 @author: Robert Frusina I pledge my honor I have abided by the Stevens Honor System ''' def binaryToNum(s): '''returns string back to n''' if s == '': return 0 elif int(s[0]) == 1: return binaryToNum(s[1:]) + 2 ** len(s[:-1]) return binaryToNum(s[1:]) + 0...
import random import sys def createOneRow(width): """Returns one row of zeros of width "width"... You should use this in your createBoard(width, height) function.""" row = [] for col in range(width): row += [0] return row def createBoard(width, height): A = [] f...
from itertools import permutations print('Enter letters: ') arr = input().split() print('Result: ') for letter in permutations(arr, ): print(letter)
fieldnames = ('name', 'age', 'job', 'pay') replyhtml = """ <html> <title>People Input Form</title> <body> <form method=POST action="cgi-bin/peoplecgi.py"> <table> <tr><th>Key <td><input type=text name=key value="%(key)s"> $ROWS$ </table> <P> <input type=submit value="Fetch", name=action> <i...