text
stringlengths
5
121k
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): ...
import random def randomWordFromTxt(): allWords = list() with open("word_list.txt", "r", encoding="utf-8") as file: for line in file: line = line.split() allWords.append(line[0]) randomWord = allWords[random.randint(0, len(allWords) - 1)] return randomWord ...
import sys class Parser: def __init__(self, text): self.text = text self.stack = [] self.a = "" self.action = "SHIFT" self.stackString = "" self.inputElement = 0 self.ac = "REDUCE TO EXP -> " self.stacklength = len(self.stack) def ...
name = str(input("Welcom to ^Make the wrong choices and you die^ Today you will be tested on 6 life or death questions. What is your name?:")) health = 1 while health > 0: action = str(input('You enter a room because you are being chased by a tiger. You close the door behind you and are immediately locked inside. Th...
colors = { 'Tista': 'Purple', 'Gia' : 'Turquoise', 'Anya':'Minty Green' } print(colors) for name , color in colors.items(): print(name + "'s favorite color is " + color) print(name + ' has ' + str(len(name)) + ' letters in her or his name') print('\n') name1 = in...
menu = [ {'item': 'Pasta', 'description': 'with sauce', 'price': 10.0}, {'item': 'Pizza', 'description': 'slices', 'price': 3.0}, {'item': 'Garlic knots', 'description': 'pieces', 'price': 1.0}, ] print(menu) print(menu[1]...
def Fibonacci0(num): """ The following is called the docstring of the function. Parameters ---------- num : int The number of elements from the Fibonacci sequence. Returns ------- None. It prints the numbers. """ a = 1 print(a) b = 1 print(b) for i in r...
str0 = 'Tista loves chocolate' print(len(str0)) print(str0[3]) print(str0[5:7]) print(str0[4:7]) str0[3] = 'z' print(str0) s2 = 'New York' zip_code = 10001 print(s2 + zip_code) print(s2 + str(zip_code)) print(s2 + ' ' + str(zip_code)) s3 = 'New York ' print(s3 + str(zip_code))
""" Created on Tue Jan 26 20:04:43 2021 @author: Caven """ class Solution: def longestMountain(self, arr: List[int]) -> int: n = len(arr) i = 0 res = 0 while i < n: base = i while i + 1 < n and arr[i] < arr[i + 1]: ...
""" Created on Mon Jul 26 16:36:29 2021 @author: Caven """ class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: node_list = [] def BFS(root): queue = deque([(root, 0,0)]) while queue: node, row, col = ...
""" Created on Mon Jun 21 21:38:02 2021 @author: Caven """ class Solution: def hammingDistance(self, x: int, y: int) -> int: return bin(x ^ y).count('1')
""" Created on Sun Sep 12 16:51:30 2021 @author: Caven """ class Solution: def findBuildings(self, heights: List[int]) -> List[int]: n = len(heights) res = [] max_height = -float('inf') for i in range(n-1, -1, -1): if heights[i] > max_height: ...
""" Created on Thu Jul 22 02:04:35 2021 @author: Caven """ class TicTacToe: def __init__(self, n: int): """ Initialize your data structure here. """ self.player1row = [0] * n self.player1col = [0] * n self.player1diag = 0 self.player1antidiag = 0 ...
""" Created on Sun Aug 16 17:38:46 2020 @author: Caven """ class Solution: def backspaceCompare(self, S: str, T: str) -> bool: def F(S): skip = 0 for x in reversed(S): if x == '#': skip +=1 elif skip: skip -=1...
""" Created on Sat Jul 31 07:53:50 2021 @author: Caven """ class Solution: def isUnivalTree(self, root: TreeNode) -> bool: if not root: return True values = [] def traverse(root): if not root: return values.a...
""" Created on Tue Sep 14 19:48:23 2021 @author: Caven """ class MaxStack: def __init__(self): """ initialize your data structure here. """ self.bucket = [] self.maxStack = [] def push(self, x): self.bucket.append(x) if len(self.max...
""" Created on Tue Aug 4 20:44:06 2020 @author: Caven """ class Solution: def isValid(self, s: str) -> bool: open_p = {'(':')', '[':']', '{':'}'} stack = [] for ss in s: if ss in open_p: stack.append(ss) elif len(stack) > 0: if ss =...
""" Created on Sat Jul 31 09:24:04 2021 @author: Caven """ class Solution: def pruneTree(self, root: TreeNode) -> TreeNode: def contains1(root): if not root: return False left_contains1 = contains1(root.left) right_contains1 = contai...
class Solution: def validPalindrome(self, s: str) -> bool: def is_palindrome(s): return s == s[::-1] l, r = 0, len(s)-1 while l < r: if s[l] == s[r]: l, r = l+1, r-1 else: return is_palindrome(s[l:r]) or is...
""" Created on Mon Nov 23 23:02:05 2020 @author: Caven """ class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() for i in range(len(nums)): if nums[i] > 0: break elif i == 0 or nums[i-1] != nums[i]: ...
""" Created on Thu May 6 21:42:36 2021 @author: Caven """ class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: n = len(A) even = 0 p = 0 while p < n: if A[p] % 2 != 1: A[even], A[p] = A[p], A[even] even += 1 ...
""" Created on Sun May 23 22:35:40 2021 @author: Caven """ class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: m = len(image) n = len(image[0]) ori_color = image[sr][sc] if ori_color == newColor: ...
""" Created on Sat Jul 31 16:51:46 2021 @author: Caven """ class Solution: def pathSum(self, root: TreeNode, targetSum: int) -> int: def backtrack(node, curr_sum): nonlocal count if not node: return curr_sum += node.val ...
import numpy as np class RegressionNetwork(object): ''' Single hidden layered neural network that applies uses the sigmoid activation functions and returns predictions for regression purposes ''' def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): self.inp...
class Tree(object): def __init__(self): self.root=TreeNode(None) self.t=[] def add(self,val): treenode=TreeNode(val) if self.root.val==None: self.root=treenode self.t.append(self.root) return else: tree_exist_node=self.t[0]...
from igramscraper.instagram import Instagram from time import sleep class Get_followers: ''' This class will recieve two seperate users as inputs then compare both of thier followers to find mutual followers. It will then return a list of followers ''' def __init__(this, user1,user2): th...
""" This module contains functions that implements generation of the game grid. Function level_of_dif determines the range (which is the representation of the level of difficulty which that will be increased thorough the test) from which the numbers will be taken. Function generate_grid generates grid, with a one spe...
class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution(): def buildTree(self, start, A): if start >= len(A): return node = TreeNode(A[start]) node.left = self.buildTree(2 * start + 1, A) node.right...
class invertBinaryTree: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: def invertBinaryTree(self, root): self.dfs1(root) def dfs(self, node): left = node.left right = node.right node.left = right node.r...
f=input() if (7*"1" in f or 7*"0" in f): print("YES") else: print('NO')
while(True): sentence = input("Enter a Sentence: ") splitsentence = sentence.split() for n in range(len(splitsentence)): if (splitsentence[n] == "-1"): raise SystemExit for x in range(len(splitsentence[n])): print(splitsentence[n][x]) ...
with open("Python.txt") as file: content = file.readlines()[2] print(content) char_count = 0 word_count = 0 line_count = 0 for char in content: char_count += 1 if char == ' ': word_count += 1 if char == '\n': line_count += 1 word_count += 1 ...
""" ### Car Brand Classification Using Deep Learning """ from tensorflow.keras.layers import Input, Lambda, Dense, Flatten from tensorflow.keras.models import Model from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.applications.resnet50 import preprocess_input from tensorflow.keras.pre...
def search(x): a = 100 z = 0 y = 0 while(x != y): y = (a + z) // 2 if (x == y): break print('Is this number larger than', +y, ' (y/n)?: ') w = input() if(w == 'y'): z = y elif(w == 'n'): a = y print("Input number is:...
import sys, random def n_refine(code, debug=True): try: code = list(map(int, code.split())) except ValueError: my_filename = sys.argv[0].replace("\\", "/").split("/")[-1] print(f"{my_filename}: Error: invalid syntax") sys.exit(1) numbers = {} i = 0 while 0 <= i < len(code): a, b = code[i]...
import sys def plus_or_minus(code, is_original): accumulator = 18 if is_original else 0 max_value = 461 if is_original else 255 for char in code: if char == "+": accumulator += 1 if char == "-": print(end=chr(accumulator)) accumulator -= 1 if accumulator < 0: accumulator = max...
import unittest class Point: def __init__(self, x, y): """ :param int x: X coordinate for the point :param int y: Y coordinate for the point """ self.x = x self.y = y class Rectangle: def __init__(self, top_left, bottom_right): """ :param Poi...
permutation = input('Put your permutation string (i.e. \"1 2 3 4\"): ') permutation = permutation.split() columns = len(permutation) new_matrix = [] for num in permutation: zeros = ['0' for _ in range(columns)] zeros[int(num) - 1] = '1' mat_row = '[ ' + ' '.join(zeros) + ' ]\n' new_matrix.append(mat_...
input_string = "Buy 1 get 2 free" new_list = [c for c in input_string] print(new_list)
class Text: def __init__(self, text): self.text = text def print_input(self): try: return print(self.text) except Exception as e: message = f"Exception in print_input: {str(e)}" print(message) raise Exception
import numpy as np from sklearn import preprocessing raw_csv = np.loadtxt('Example_TF.csv', delimiter = ',') unscaled_inputs_all = raw_csv[:,1:-1] targets_all = raw_csv[:,-1] num_one_targets = int(np.sum(targets_all)) zero_targets_counter = 0 indices_to_remove = [] for i in range(targets_all.shape...
b = True b2 = False i = 2 i.bit_length() f = 2.5 f.is_integer() s = "Hola!" s.isdecimal() s.isdigit() s.isalnum() s.islower() s.isupper() t = (s, i) t.count() l = [] l.count() l.append() l.remove() l.reverse() l.clear() l.insert() d = { "Key":2, "Hola":"Value"} d.clear() d.get() d.keys() d.values(...
""" __Author__: Romain Maillard __Date__: 29.09.2017 __Name__: control_musicProgress.py __Description__: Get the actual music, display it and control startTime and bar """ import time from threading import Thread class MusicProgress(Thread): ''' Class MusicProgress functions: - run...
""" @reroes Manejo de estructuras """ diccionario = {"nombre": "Fernando", "apellidos": "Quizhpe"} print("Imprimir diccionario") print("%s: %s %s: %s" % ("Mi nombre es", diccionario["nombre"], \ "y mi apellido es", diccionario["apellidos"]) \ )
import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv("E:/AI_ML_DA/R_Python_Code_Datasets/DataSets/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/Section 2 -------------------- Part 1 - Data Preprocessing --------------------/Data.csv") dataset.head() X = dat...
numbers= tuple(input("Enter numbers for tuple").split(",")) for n in numbers: if int(n)%5==0: print(n)
import time def max_freq(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) max_freq_word = '' max_count = 0 for key in result: if result[key] > max_count: max_count = result[key] max_freq_word = key print(f'Most ...
"""Mergesort not in place.""" import math from typing import List def merge(A: List[float], p: int, q: int, r: int) -> None: """Split A at q and merge together in order.""" n_1 = q-p+1 n_2 = r-q L = [] R = [] for i in range(n_1): L.append(A[p+i]) for j in range(n_2): R.appe...
import math import time import random def coin_greedy(n): coins = [1, 2, 5, 10, 25][::-1] res = 0 for coin in coins: res += n // coin n %= coin return res def coin_dynamic(n): coins = [1, 2, 5, 10, 25] if n == 0: return 0 known_values = [math.inf for idx in ...
from functools import reduce import operator def parse_food(l): l = l.strip()[:-1] ingredients, allergens = l.split(" (contains ") return ingredients.split(), allergens.split(", ") with open("day21-input.txt") as f: foods = [ parse_food(l) for l in f ] allergens = {} for i, a in foods: for alle...
def rotate_digits(num: int) -> int: if num < 0 or num > 10000: return 0 bad_numbers = [0, 1, 3, 4, 7, 8] counter = 0 good_numbers = 0 while counter != num: new_list = [i for i in str(counter)] for i in new_list: ...
def max_capicity(weights: list, days: int) -> int: max_capicity = sum(weights) // days counter = 0 daily_weight = 0 cur_days = 1 while counter != len(weights): if weights[counter] > max_capicity: max_capicity += 1 ...
''' 1) Array and pointers(?) How are arguments passed in functions (call by value or reference) What happens when: Def: Foo (a): a[3]=10 return a = [1,2,3,4,5] foo(a) Print (a) Def foo (a): print(id(a)) Assume variable “a” ultimat...
'''Classes and functions to handle events. Class Event is a generic class for all types of events. Class Event is expected to be specialized into different, more specific types of events, implemented as subclasses. A hierarchy of event types and subtypes is possible. Events are distinguished by a nickname, a descri...
from enemy import Enemy import random class Vader(Enemy): def __init__(self, n, h): super(Vader,self).__init__(n, h) self.attack_dic = {'saber throw' : 5, 'force choke' : 10, 'saber slash' : 8} self.attack_name = None ...
from enemy import Enemy class Dragon (Enemy): def __init__(self,n,h): super(Dragon,self).__init__(n,h) self.attack_name= 'Fire breadth' self.damage = 10 def __str__(self): return str(self.name) + " " + str(self.health) def attack(self): ...
""" Created on Thu Sep 19 15:28:51 2019 @author: Anusha """ sum = 0 for i in range(0,101,2): sum += i print(sum)
board = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,9], [0,0,0,6,0,1,0,7,8], [0,0,7,0,4,0,2,6,0], [0,0,1,0,5,0,9,3,0], [9,0,4,0,6,0,0,0,5], [0,7,0,3,0,0,0,1,2], [1,2,0,0,0,7,4,0,0], [0,4,9,2,0,6,0,0,7] ] def solve(bo): print(bo,"\n") find=find_empty(bo) if not find: ...
""" Move all Zeros to the end of the array, maintaining the relative orders of other elements Time Complexity :O(n) Space Complexity :O(1) inplace algorithm inp = arr = [1, 3, 0, 3, 0, 5, 12] out = 1->3->3->5->12->0->0 """ def MoveZeros(arr): arrLen = len(arr) print(arrLen) if arrLen <= 0: return...
import sys class Node: def __init__(self, data): self.data = data self.left = None self.right = None MIN = -sys.maxsize - 1 MAX = sys.maxsize def constructBST(postorder, postIndex, key, min, max, size): if postIndex[0] < 0: return None root = None ...
side = int(input("Please Enter any Side of a Square : ")) print("Square Number Pattern") for i in range(side): for i in range(side): print('1', end = ' ') print()
def merge_sort(l, comparator=lambda x, y: x < y): def split(l): if len(l) < 2: return l left = l[ : len(l) // 2 ] right = l[ len(l) // 2 : ] sorted_left = split(left) sorted_right = split(right) return(merge(sorted_left, sorted_right)) def...
class Solution: def longestCommonPrefix(self, nums): nums=sorted(nums,key=len) for i in nums: print(i[0]) s=Solution() print(s.longestCommonPrefix(["flowerss","flow","flighjt"] ))
import datetime import time current_time=datetime.datetime.now() print("start time is ",current_time) def reverse_def(s): if len(s)<=1: print("Computing {}...".format(s)) return s print("Computing {}...".format(s)) return reverse_def(s[1:]) + s[0] res=reverse_def("ab...
def fact(n): print("bhai pehla base case",n) if n==0: print("yha mat aao",n) return 1 print("ye aap ki baap ki jagah hau",n) return n*fact(n-1) print(fact(6))
coin = 0 while True: print("You have {} coins".format(coin)) want = input("Do you want a coin? ") if want == "yes": coin += 1 elif want == "no": break print("Bye")
file_name = input("Enter name of file you would like to write: ") def writer(file_name): file_handle = open(file_name, 'w') file_handle.write(file_name) file_handle.close() print(file_name) writer(file_name)
class Person(): greeting_count = 0 def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone self.friends = [] self.num_unique_people_greeted = 0 self.uniquecounter = [] def greet(self, other_person): ...
from random import * from math import * from turtle import * def repeat(times, f): for i in range(times): f() def smaller(): width(randint(2, 7)) def walk(): goto(randint(-300, 300), randint(-300, 300)) def star(size): for i in range(5): def nifty(): for x in range(11, 55,...
a = "i am a string" for i in reversed(a): print (i, end="") print("")
def divide(a=5,b=3): c=a/b print(c) divide(b=4,a=8)
def function(): i=int(input("enter the number")) fac=1 while i>0: fac=fac*i i=i-1 print("factorial","=",fac) function()
import matplotlib.pyplot as plt def my_draw_a_vector_from_origin(v): plt.axes().set_aspect('equal') x=[0,v[0]] y=[0,v[1]] plt.xlim(-10,15) plt.ylim(-10,15) plt.plot(x,y) def my_draw_a_vector_from_v_to_w(v,w): x=[v[0],w[0]] y=[v[1],w[1]] plt.xlim(-10,15) plt.ylim(-10,15...
import tkinter import random canvas_width = 640 canvas_height = 480 canvas = tkinter.Canvas(width=canvas_width, height=canvas_height) canvas.pack() number = random.randint(1,6) print("Number {}".format(number)) print("Making dice") size = 255 x, y = canvas_width / 2, canvas_height / 2 unit = size / 5 radius = size...
import random class Board: """ Board class to represent nodes and work with them """ def __init__(self, param=None): if param: self.from_list(param) else: numbers_array = list(range(9)) random.shuffle(numbers_array) self.from_list(number...
sentence = "This is a String" print(sentence.lower()) print(sentence.capitalize()) print(sentence.upper()) print(sentence.upper().isupper()) print(len(sentence)) print(sentence[3]) print(sentence.index("S")) print(sentence.replace("This" , "Thus")) print(sentence.replace("i" , "U"))
def maxFunc (num1,num2,num3): return max(num1,num2,num3) input1 = input("Enter a number: ") input2 = input("Enter a number: ") input3 = input("Enter a number: ") maxNum = maxFunc(int(input1),int(input2),int(input3)) print("the largest value is: " + str(maxNum))
from operator import add, mul, truediv as div def calculate(operators): operators = { '+': add, '/': div, '*': mul, } number1 = int(input("Pick a number")) number2 = int(input("Pick another number")) question = str(input("What is") + number1 + operators + number2)
import numpy as np import os import argparse np.set_printoptions(threshold=np.nan) def main(): parser = argparse.ArgumentParser(description="Load numpy file and display its data in numpy array.") parser.add_argument("input_file", help="numpy file to load and display data from") args = parser.p...
hours = input("Enter Hours:") hrs = float(hours) rate = input("Enter rate per hour:") rte = float(rate) if hours > 40 : pay = 40 * rte +(rte * 1.5 * (hrs-40)); print(pay) else: pay = hrs * rte print(pay)
fname = input("Enter file name: ") fhandle = open(fname) line = fhandle.read() upline = line.upper().rstrip() print(upline)
print('2자리의 양수를 입력하세요.') while True: no = int(input('값을 입력하세요.: ')) if not(no < 10 or no > 99): break print(f'입력받은 양수는 {no}입니다.')
import sys class Node: def __init__(self, data): self.right=self.left=None self.data = data class Solution: def insert(self,root, data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left, data) ...
def run(input, output): from abc import ABCMeta, abstractmethod class Book(object, metaclass=ABCMeta): def __init__(self, title, author): self.title = title self.author = author @abstractmethod def display(): pass class my_book(Book): ...
"""animation.py contains different animations with timelines we wish to play, similar to sprites, though, we're using sprites as still images rather than sprite sheets, hence this file.""" import pygame from Displays import Display import Sprites class Animation: def __init__(self, x,y, type, gridObj): self.x = x...
import radio from random import randint from microbit import * import neopixel flash = [Image().invert()*(i/9) for i in range(9, -1, -1)] radio.on() np = neopixel.NeoPixel(pin0, 16) while True: incoming = radio.receive() if incoming == 'flash': red = 0 green = 0 blue = 0 ...
print('addition by 1') for i in range(12,16): print(i) print('addition by 2') for i in range (0, 11, 2): print(i) print('subtraction') for i in range(5, -1, -1): print(i)
file=open("abc.txt","r") line=file.readlines() for result in line: print(result) file.close()
from collections import defaultdict lines = open('./6.txt').read().splitlines() orbit_pairs = [s.split(')') for s in lines] def create_adjacency_list(orbit_pairs): """Returns a graph from orbit pairs based on the root COM.""" tree = defaultdict(list) for pair in orbit_pairs: t...
from util import * from setting import * import pygame from copy import deepcopy class Map: def __init__(self, width, height): self.width = width self.height = height self.InitMap = initGame() loading_map = [] self.data = [[loading_map for y in range(height)] for x i...
lst = [1, 2, 3, 4, 5] lst_2_1 = [] lst_2_2 = [] first_item = lst.pop(0) length = len(lst) temporary = 0 while length > 0: item = lst[temporary] lst_2_1.append(item) temporary += 1 length -= 1 else: lst_2_1.append(first_item) print(lst_2_1) for i in lst: lst_2_2.append(i) else: lst_2_...
class Func: def __init__(self, arg1, arg2, operator): self.arg1 = arg1 self.arg2 = arg2 self.operator = operator def process(self): if self.operator == '+': return self.add() elif self.operator == '-': return self.subtract() elif self.oper...
d = ['a', 'man', 'and', 'a', 'woman'] list(set(d))
amount, unit = input('Enter amount with units: ').split()[:2] converted_data = int(amount) * {'in': 2.54, 'cm': 0.39}[unit]
def thing(list_): temp = enumerate(max(x) - min(x) for x in list_) return max(x[::-1] for x in temp)
print('&lt;a href="http://www.example.com"&gt;example text&lt;/a&gt;')
slice(*[{True: lambda n: None, False: int}[x == ''](x) for x in (mystring.split(':') + ['', '', ''])[:3]])
kwargs = dict((k, getattr(self, k)) for k in ('c', 'd') if getattr(self, k)) print_something(a, b, **kwargs)
os_list = ['osxx', 'centos', 'windowsx'] df.rename(columns=lambda x: x+'x' if x in os_list else x)
for i in range(1,len(nList)): for distance in nList[i]: outputLlist.append('{} metres, {} metres, {} seconds'.format(*distance))