text
stringlengths
5
121k
def count_datatypes(*args): lst=[type(i) for i in args] return [lst.count(i) for i in (int, str, bool, list, tuple, dict)] print(count_datatypes(1, 45, "Hi", False) ) print(count_datatypes([10, 20], ("t", "Ok"), 2, 3, 1) ) print(count_datatypes("Hello", "Bye", True, True, False, {"1": "One", "2": "Two"...
def first_and_last(s): t=sorted(s) e=''.join(t) r=e[::-1] p=e,r return list(p) print(first_and_last("marmite")) print(first_and_last("bench")) print(first_and_last("scoop"))
def boom_intensity(n): if n<2: return 'boom' elif n%2==0 and n%5==0: return 'B'+'O'*n+'M'+'!' elif n%2==0: return 'B'+('o'*n)+'m'+'!' elif n%5==0: return 'B' + ('O' * n) + 'M' else: return 'B'+('o'*n)+'m' print(boom_intensity(4) ) print(boom_intensit...
def check(lst): posi = sorted(lst) for i in range(0,len(lst)-1): first=posi.pop(0) posi.append(first) if posi==lst: return "YES" return 'NO' print(check([3, 4, 5, 1, 2])) print(check([1, 2, 3])) print(check([7, 9, 11, 12, 5]) )
def reverse_odd(string): new_lst=string.split() s='' for i in new_lst: if len(i)%2!=0: t=i[::-1] s=s+t+' ' else: s=s+i+' ' return s.strip() print(reverse_odd("Bananas")) print(reverse_odd("One two three four")) print(reverse_odd("Make sure uoy on...
class A: def feature1(self): print('Feature 1 working') def feature2(self): print('Feature 2 working') class B(): def feature3(self): print('Feature 3 working') def feature4(self): print('Feature 4 working') class C(A,B): def feature5(self): print('Feature...
def scale_tip(lst): t=len(lst)//2 l= sum(lst[0:t]) r=sum(lst[t+1:]) if l>r: return 'left' elif l<r: return 'right' else: return 'balanced' print(scale_tip([0, 0, "I", 1, 1])) print(scale_tip([1, 2, 3, "I", 4, 0, 0])) print(scale_tip([5, 5, 5, 0, "I", 10, 2, 2, ...
import pandas as pd df = pd.read_csv('winequality-red_2.csv') df = df.drop(columns = ['Unnamed: 0']) df.head() print('Q1 of wines from Stellenbosch:',df[df['region'].str.contains('Stellenbosch')].shape[0]) filterDF = df[(df['sulphates']<=0.6) & (df['price']<20)] print("Q2 avg price of wines fro...
old_blueprint = { "Kitchen": ['Dirty', 'Oak', "Damaged", "Green"], "Dining Room": ['Dirty', 'Pine', 'Good Condition', 'Grey'], "Living Room": ['Dirty', 'Oak', 'Damaged', 'Red'], "Bedroom" : ["Clean", 'Mahogany', 'Good Condition', 'Green'], "Bathroom": ["Dirty", 'White Tile', 'Good Condition','W...
car = "lexus" anotherCar = input("What is your car name?") print(f"cool! My favorite car is {car} and yours is {anotherCar}") GRAVITY = 9.8 GRAVITY = input(f"gravity value:") print(f'gravity is {GRAVITY}')
import random from wonderwords import RandomWord SNOWMAN_WRONG_GUESSES = 7 SNOWMAN_MAX_WORD_LENGTH = 8 SNOWMAN_MIN_WORD_LENGTH = 5 SNOWMAN_GRAPHIC = ['* * * ', ' * _ * ', ' _[_]_ * ', ' * (") ', ' \( : )/ *', '* (_ : _) ', '-----...
import numpy as np def RadixSort(L, ord): Reloader_List = [] temp = [] for i in range(0, 10): Reloader_List.append([]) for i in range(0, ord): print('Iteration ', i, ' : ', L) for ele in L: n = int((ele / np.power(10, i)) % 10) Reloader_List[n].appen...
import matplotlib.pyplot as plt import numpy as np from sympy import symbols from sympy import lambdify from sympy import sympify x = symbols('x') a = int(input('Introduzca a = ')) b = int(input('Introduzca b = ')) n = int(input('Introduzca n = ')) expr = input('Introduzca f(x) = ') expr = sympify(expr) f = lamb...
n = list(input()) for i in n: if i == '1': print(9, end='') elif i == '9': print(1, end='') print()
a = [int(input()) for _ in range(3)] l = sorted(a, reverse=True) print(l.index(a[0]) + 1) print(l.index(a[1]) + 1) print(l.index(a[2]) + 1)
x = int(input()) money = 100 ans = 0 while True: money += int(money*0.01) ans += 1 if money >= x: break print(ans)
numberList = [] while True: newInt = input() if newInt == '.': break else: numberList.append(int(newInt)) print(sum(numberList) / len(numberList))
n = int(input("Enter the value of n: ")) a = 0 b = 1 c = 0 count = 1 print("Fibonacci Series: ", end = " ") while(count <= n): print(c, end = " ") count += 1 a = b b = c c = a + b
from Bio import SeqIO, SeqRecord import argparse def duplicate_remover(file): d = {} duplicate = [] for record in SeqIO.parse(file, "fasta"): if record.seq in d.keys(): print("duplicate found : \n" + record.id) duplicate.append(record.id) d[record.seq] = record.desc...
from matplotlib import pyplot as plt def generateGraphe(): plt.xlabel('K') plt.ylabel('paquets transmis') plt.title('Asynchrone Aloha Statistics') plt.legend() plt.savefig('graphe.png') plt.show()
class Account(): def __init__(self, owner, balance): Account.owner = owner Account.balance = balance def __repr__(self): return f"owner:{self.owner}, balance:{self.balance}" def deposit(self, deposit): self.balance = self.balance + deposit print('Succeed') ...
i = int(input('number: ')) p = 1 while i >= p: print('*' * p) p = p+1
import numpy as np import itertools from functions import * import matplotlib.pyplot as plt from matplotlib import animation H_p = 2 H_c = 1 dt = 1 x = [0] y = [0] v = [0] phi = [0] goal = [-5, -5] k = 0 goalReached=False obstacles = [[0, 1], [2, 1]] min_buffer = 0.1 def printAllKLength(set, k): i...
class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList:...
import string print("============ str.format() ===============") print() s0 = "{} 's age is {}" s1 = "{0} 's age is {1}" s2 = "{0!a} 's age is {1}" print(s0) print(" --> ",s0.format("呉剣",40)) print(s1) print(" --> ",s1.format("呉剣",40)) print(s2) print(" --> ",s2.format("呉剣",40)) print() print("...
''' 协程(Coroutine)测试 - 生产者和消费者模型 ''' def consumer(): r = '' while True: n = yield r if not n: return r = '200 OK' def produce(c): c.send(None) n = 0 while n < 5: n = n + 1 print('[PRODUCER] P...
class Employee: def __init__(self,first, last, pay): self.first =first self.last =last self.pay =pay self.email = first[0] + '.'+ last +"@hackmanmfb.com" def fullname(self): return '{} {}'.format(self.first, self.last) emp1 =Employee('david','igbokwe',50000) emp2 = Employee('Emeka', 'Victor',60000) ...
def normalize(data, mean, std): data = (data - mean) / std return data def denormalize(data, mean, std): data = (data * std) + mean return data
import pandas as pd import seaborn as sn import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score dataset = pd.read_csv('data.csv') X = dataset.iloc[:, 2:].values Y = dataset.iloc[:, 1].values print("Dataset dimensions : {}".format(dataset.shape)) dataset.hist(bins = 10, figsize=(20, 15)) plt.sho...
class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: if not points: return 0 points.sort(key = lambda x : x[1]) arrows = 1 first_end = points[0][1] for x_start, x_end in points: ...
class Solution: def reverseBetween(self, head: ListNode, l: int, r: int) -> ListNode: if not head or l == r: return head dummy = prev = ListNode(0) dummy.next = head for _ in range(l - 1): prev = prev.next reverse = None cur = prev.next ...
""" # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: ...
class DLinkNode: def __init__(self): self.key = None self.val = None self.before = None self.after = None class LRUCache: def __init__(self, capacity: int): self.maxi = capacity self.size = 0 self.head = DLinkNode() self.tail = DLink...
class Solution: def isPowerOfFour(self, num: int) -> bool: return num > 0 and num & (num-1) == 0 and 0b1010101010101010101010101010101 & num == num def isPowerOfFour(self, num: int) -> bool: if num < 0 : return False def helper(num): if num < 4: if num ==...
class Solution: def largestBSTSubtree(self, root: TreeNode) -> int: def dfs(root): if not root: return 0, float('inf'), float('-inf') l_n, l_min, l_max = dfs(root.left) r_n, r_min, r_max = dfs(root.right) if l_ma...
class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': self.p_find, self.q_find= False, False res= self.dfs(root, p, q) return res if (self.p_find and self.q_find) else None def dfs(self, root, p, q): ...
class Node: def __init__(self, key=None, val=None, before=None, after=None): self.key = key self.val = val self.before = before self.after = after class LRUCache: def __init__(self, capacity: int): self.cache = {} self.maxi = capacity self.head = Node()...
from neuronalApp.netCar.abstractNetCar.abstractVehicle import abstractVehicle class Car(abstractVehicle): color = (255, 0, 0) def __init__(self, xpos, ypos, velocity): self.velocity = velocity self.position = (xpos, ypos) self.direction = (0, 0) def move(self): ...
import sys def two_sum(sequence): result = None for i in range(len(sequence)): for j in range(1, len(sequence)): if i != j and sequence[i] == -sequence[j]: result = i+1, j+1 if result is not None: return (result[0], result[1]) if result[0] < result[1] else (resu...
import sys def count_word_occurence(words): count = {} for word in words: count[word] = count.get(word, 0) + 1 return count if __name__ == "__main__": if len(sys.argv) != 2: print("Invoke the program passing a path to a file as an argument") else: with open(sys.argv[1]) a...
import sys def motif_occurrence(dna, motif): result = [] for i in range(0, len(dna)): stripped = dna[i:i+len(motif)] index = stripped.find(motif) if index >= 0: result.append(index + i + 1) return result if __name__ == "__main__": if len(sys.argv) != 2: pr...
import sys def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) if __name__ == "__main__": if len(sys.argv) != 2: print("Invoke the program passing a path to a file as an argument") else: with open(sys.ar...
def get_weather_icon(pct_rain): """ Given the percent chance of rain as an integer (e.g. 75 is 75%), return the name of the icon to be displayed.""" if int(pct_rain) <= 10: return 'fullsun.ico' elif int(pct_rain) <= 20: return 'suncloud.ico' elif int(pct_rain) <= 85: return 'twodrops.ico' el...
def accum(s): text = [] for i in range(len(s)): temp = s[i] * (i + 1) text.append(temp.capitalize()) new_s = '-'.join(text) return new_s b = accum('abcd') print(b)
def timeformat(seconds): minutes = 0 hours = 0 if seconds / 60 >= 1: for i in range(0, seconds, 60): if seconds - 60 < 0: break else: minutes += 1 seconds -= 60 if minutes == 60: hours += 1...
import time import numpy as np import sympy class GD(): def __init__(self): self.variant='x y z' self.inivalue=[1,2,3] self.fvalue=0 self.f=sympy.simplify('x**2+y**3+z') def fun1(self,x): variant=self.variant.split(' ') for i in range(0,len(x)): if ...
import copy original = ["one", "two", ["three", "333"]] shallow = copy.copy(original) deep = copy.deepcopy(original) assert (original == shallow) assert (original == deep) assert (shallow == deep) original[2][0] = "four" assert (original == shallow) assert (original != deep) assert (shallow != deep) clas...
"""This is a simple class with some attributes to calculate area and circumference for a circle.""" __author__ = "Otto Mättas" __copyright__ = "Copyright 2021, The Python Problems" __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Otto Mättas" __email__ = "otto.mattas@eesti.ee" __status__ = "Development" ...
import pandas as pd from sklearn.preprocessing import MinMaxScaler training_data_df = pd.read_csv("Training.csv") test_data_df = pd.read_csv("Testing.csv") scaler = MinMaxScaler(feature_range=(0, 1)) scaled_training = scaler.fit_transform(training_data_df) scaled_testing = scaler.transform(test_data_df) prin...
def search(nums, target): low = 0 high = len(nums) - 1 while low <= high: mid = low + (high - low) // 2 if target == nums[mid]: return mid elif nums[mid] <= nums[high]: if( target > nums[mid]) & (target <= nums[high]): low = mid + 1 ...
def findMaxLength(nums): hash_map = {} curr_sum = 0 max_len = 0 ending_index = -1 n = len(nums) for i in range (0, n): if(nums[i] == 0): nums[i] = -1 for i in range (0, n): curr_sum = curr_sum + nums[i] if (curr_sum == 0): ...
from itertools import dropwhile def id_consonants(x): return x not in 'aeiouy' def vowel(name): schop = ''.join(dropwhile(id_consonants, name)) if len(schop) > 1 and schop[0] == 'y' and schop[1] in 'aeiou': return schop[1:] elif len(name) > 0 and schop == '': return name elif...
def is_prime(a): b = 0 for i in range(int(pow(a, 0.5))): if a % (i+2) == 0: if a != (i+2): b = 1 if b == 1 or a == 1: return False if b != 1: return True sol = 0 for j in range(1000): if is_prime(j): sol = sol + j print(sol)
def is_prime(a): b = 0 for i in range(int(pow(a, 0.5))): if a % (i+2) == 0: if a != (i+2): b = 1 if b == 1: return False if b != 1: return True
""" translation to cpp nothing is new in this file, howmany left function uses the exact same for loops as the board creation function, use it a reference, also the ValidBlack or red fuctions do the same nopossible moves functions also there is nothing new the interesing part is the returns, 1 if player has...
import numpy as np import matplotlib.pylab as plt class PerceptronClassifier: def __init__(self, alpha, t , x): self.alpha = alpha self.weight = np.random.uniform(-1.0, 1.0, 3) self.x = x self.t = t self.plot_pixels() def plot_pixels(self): ...
import re def word_count(sentence): split_sentence = re.split(' +| *\n *|\t', sentence) output = {} for x in split_sentence: output[x] = count_word(x, split_sentence) return output def count_word(word, iterable): count = 0 for x in iterable: if x == word: count += 1...
class Solution: def isAnagram(self, s: str, t: str) -> bool: if sorted(s) == sorted(t): if 1<=len(s)<=(5*pow(10,4)): return True else: if 1<=len(s)<=(5*pow(10,4)): return False s = Solution() s.isAnagra...
import csv import os import numpy as np electionfile = os.path.join("Resources", "election_data.csv") candidates = [] votes = [] filetype = "main" poll = {} total_votes = 0 with open(electionfile, newline="") as csvfile: election = csv.reader(csvfile, delimiter=",") election_header = next(election) ...
s = input('Enter a string: ') L = ['darn','dang','freakin','heck','shoot','Darn','Dang','Freakin','Heck','Shoot'] for i in range(len(s)): for t in L: if t in s: s = s.replace(t,len(t)*'*',-1) print(s) s = input('Enter a string: ') s = s.lower() L = ['darn','dang','freakin','heck...
class Calculator: def add(a,b): return a+b def sub(a,b): if(a>b): return a-b else: return b-a def mul(a,b): return a*b def div(a,b): return a/b def mod(a,b): return a%b x=add(4,5) print(x) y=sub(6,7) print(y) z=mul(3,2) print(z) c=div(4,2) print(c) d=mod(4,2) print(d)
import socket ip_address_list = ['31.13.74.36', '172.217.14.174', '40.97.142.194'] for ip in ip_address_list: print("Begin IP Scan on: " + ip + ".") try: for port in range(1,1000): aSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) aSoc...
'''This file handles the menus; it prints out the users options and calls the methods required when the relevant option is chose. Essentially this is the 'control tower'. ''' from core.roundClass import user_round from core.dbManager import db from core.preferenceClass import pref from core.utils import clearScre...
square = 1 while square <= 5: print('*' * 5) square += 1
try: total_bill = int(input('What was your total? ')) service = input('What was the service bad, fair, or good? ') split = input('How many people will be paying? ') except: print('error') split = int(split) tip = () service = service.lower() if service == 'bad': tip = total_bill...
weight = float(input("what is the weight of the package in pounds?")) if weight <= 2: newWeight = weight * 1.50 print("you pay $ " + str(newWeight)) elif weight >2 and weight <=6: newWeight = weight * 3 print("you pay $ " + str(newWeight)) elif weight >6 and weight <=10: newWeight = weight * 4 print(...
import unicodedata def filter_accents(text): """Return a sequence of accented characters found in the passed in lowercased text string """ accents = [] for char in text: if "WITH" in unicodedata.name(char): accents.append(char.lower()) return accents
import textwrap import itertools COL_WIDTH = 20 def _pad(string, width=COL_WIDTH): length = len(string) if length > width: raise ValueError return string + " " * (width - length) def _pad_list(lst, width=COL_WIDTH): return [_pad(line) for line in lst] def text_to_columns(text): """Spl...
import pandas as pd data = "https://s3.us-east-2.amazonaws.com/bites-data/menu.csv" df = pd.read_csv(data) pd.options.mode.chained_assignment = None def get_food_most_calories(df=df): """Return the food "Item" string with most calories""" return df["Item"].loc[df["Calories"].idxmax()] def get_bodybuild...
import itertools def find_number_pairs(numbers, N=10): return [pair for pair in itertools.combinations(numbers, r=2) if sum(pair) == N]
from datetime import datetime import os import urllib.request SHUTDOWN_EVENT = "Shutdown initiated" logfile = os.path.join(os.getcwd(), "log") urllib.request.urlretrieve( "https://bites-data.s3.us-east-2.amazonaws.com/messages.log", logfile ) with open(logfile) as f: loglines = f.readlines() def convert_t...
import csv import requests from collections import Counter CSV_URL = "https://bites-data.s3.us-east-2.amazonaws.com/community.csv" def get_csv(): """Use requests to download the csv and return the decoded content""" with requests.get(CSV_URL) as r: content = (line.decode("utf-8") for line in ...
from datetime import datetime, timedelta PY2_DEATH_DT = datetime(year=2020, month=1, day=1) BITE_CREATED_DT = datetime.strptime('2018-02-26 23:24:04', '%Y-%m-%d %H:%M:%S') def py2_earth_hours_left(start_date=BITE_CREATED_DT): """Return how many hours, rounded to 2 decimals, Python 2 has left on Planet Ea...
""" Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. Example 1: Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation:...
""" Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Input: [1,3,5,6], 5 Output: 2 Input: [1,3,5,6], 7 Output: 4 Input: [1,3,5,6], 0 Output: 0 Input: [1,3,5,6], 7 Out...
dic = {} if dic[f]: print ('it is true') else: print ('it is false')
""" Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] """ class TreeNode(object): ...
""" There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you shou...
""" Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. Example: Input: ...
''' Generate sales for toy example (Experiment #2) carlos.aguilar.palacios@gmail.com ''' import numpy as np import seaborn as sns import matplotlib.pyplot as plt import scipy from sklearn.preprocessing import MinMaxScaler import pandas as pd def Gompertz_distribution(t=np.linspace(0, 5, 50), b_scale=1, eta_sh...
class GradeRepo: """ Class for grade repositories """ def __init__(self): """ Constructor """ self._data = [] def __len__(self): """ Returns the length of the repository """ return len(self._data) def __str__(self): """ ...
def write_story(intent, utter, file, iterations=1): result_string = '' for i in range(iterations): name = input("What concept: ").strip('\n') utter_name = name.replace(' ', '_') result_string += f'\n## {intent} {name}\n' + \ f'* {intent}\n' + \ ...
class User: def __init__(self, user, objs): self.user = user self.players = objs self.preferences = [] def add_obj(self, new_obj): self.players += new_obj def add_preferences(self, preferences): """Trying an ordered list of preferences""" self.preferences =...
def gcd(x:int, y:int) -> int: if x < y: x, y = y, x if y == 0: return x else: return gcd(y, x%y) if __name__ == '__main__': x = int(input('x : ')) y = int(input('y : ')) print(f'gcd(x,y) = {gcd(x,y)}')
from typing import MutableSequence def qsort(a: MutableSequence, left: int, right: int) -> None: pl = left pr = right x = a[(left + right) // 2] while pl <= pr: while a[pl] < x: pl += 1 while a[pr] > x : pr -= 1 if pl <= pr: a[pl], a[pr] = a[pr], a[pl] ...
num = raw_input("Enter your number: ") option = raw_input(" hex to binary(1)\n binary to hex(2)\n hex to decimal(3)\n binary to decimal(4)\n decimal to binary(5)\n decimal to hex(6)\n") if option == str("1"): print(bin(int(num, 16))) elif option == str("2"): print(hex(int(num, 2))) elif option == str("3"): prin...
cnp=str(input('Introduceti CNP-ul persoanei: ')) if cnp.isnumeric() and len(cnp) == 13: print('CNP-ul este corect') else: print('CNP-ul este gresit')
import random part3 = ['ocean', 'jump', 'computer', 'chair', 'rope'] selected_word = random.choice(part3) letters = list(selected_word) characters = len(letters) def printblanks(num): for x in range(num): print('_', end=' ') print() printblanks(characters) def checkletters(num): if (num > 1): print('Plea...
listofnum = [2,4,1,5,6,40,-1] num = int(input("Which number you want as a product : ")) i=None j = None for i in range(len(listofnum)): if num%listofnum[i]==0: if num/listofnum[i] in listofnum: print('The numbers multiplied are : ',listofnum[i],'and',int(num/listofnum[i...
from collections import deque class GraphNode: def __init__(self,value): self.val = value self.adjacent = [] class GraphOperations: def __init__(self): print("Graph operations classe is initialized") self.graph = set() def addEdge(self,source,destination): ...
grid1 = [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] grid3 = [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]] def get_rectangle_position(grid): start_ro...
class WordSearch: def __init__(self,grid): self.grid=grid self.directions = [[0,-1],[-1,0],[0,1],[1,0]] self.R = len(grid) self.C = len(grid[0]) print(self.grid) def searchWord(self,word,row,col,position): if row<0 or row>=self.R or col<0 or col>=sel...
def find_embedded_word(words_, data): for word in words_: hashed = get_hash_map_data(data) is_found = True for char in word: if char not in hashed or hashed[char] == 0: is_found = False break elif char in h...
def main (): nota1 = int(2) nota2 = int(8) soma = nota1 + nota2 media = soma / 2 if media >= 5: print ("passou") else: print ("Bombou") main()
""" DEQUE Abstract Data Type DEQUE = Double ended Queue High level its combination of stack and queue you can insert item from front and back You can remove items from front and back we can use a list for this example. we will use methods >----- addfront >----- add rear >----- remove front >----- remove rear we...
class Queue(object): def __init__(self): self.item = [] def enqueue(self, item): self.item.insert(0, item) def dequeue(self): if self.item: self.item.pop() else: return None def peek(self): if self.item: return self.item[-1...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: p1 = head p2 = None while p1 != None: p3 = p1.next p1.next = p2 p2 = p1 p1 = p3 ...
import gmsh import matplotlib.pyplot as plt import math def distance(p1, p2): x = abs(p1[0]-p2[0]) y = abs(p1[1]-p2[1]) return max(x,y) def euclidean(p1, p2): return (math.sqrt((p1[0]-p2[0]) ** 2 + (p1[1]-p2[1]) ** 2)) def add(p1, p2): x = p1[0]+p2[0] y = p1[1]+p2[1] ret...
import pygame from pygame.locals import * import sett from music import * pygame.init() class Button: def create_button(self, surface, color, x, y, length, height, width, text, text_color): """Responsible for creating the button. Accepts the fo...
""" Created on Tue Jul 8 @author: Ancient Abysswalker """ from math import floor def isPalindrome(number): number=str(number) for digit in range(0,floor(len(number)/2)): if number[digit] != number[-1-digit]: return False return True maxMult=999 maxPalindrome=0 ...