text
stringlengths
37
1.41M
def friendCircles(friendships): count = 0 visited = set() for person in range(len(friendships)): if person not in visited: count += 1 dfs(person, friendships, visited) return count def dfs(node, friendships, visited): for person, is_friend in enumerate(friendships[n...
import sys sys.path.append('../queue2') sys.path.append('../stack') from queue2 import Queue from stack import Stack """ Binary search trees are a data structure that enforce an ordering over the data they store. That ordering in turn makes it a lot more efficient at searching for a particular piece of data in the t...
from Calculators import division from Calculators import multiplication from Calculators import summation from Calculators import subtraction class Calculator(): def summa(a,b): print (summation.Summation.summa(a, b)) def devis (a,b): print(division.Divisions.divis(a,b)) def m...
def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts text = input("Herhangi bir metin giriniz: ") sayac = "" for harf in text: if harf not in sayac: ...
class Ogrenci: def __init__(self,numara,ad,soyad,sinif): self.ad=ad self.soyad=soyad self.numara=numara self.sinif=sinif self.derslistesi=[] def dersEkle(self,ders): self.derslistesi.append(ders) class Hoca: def __init__(self,ad,soyad): se...
sentence = input("Enter a sentence :") numberOfWovels = 0 numberOfConsonants = 0 for i in range(len(sentence)): if sentence[i] == "a" or sentence[i] == "e" or sentence[i] == "i" or sentence[i]=="ı" or sentence[i]=="u" or sentence[i]=="ü" or sentence[i] == "o" or sentence[i]=="ö": numberOfWovels = numberOfWove...
#Descobrindo os números primos em um range a = int(input('Digite o primeiro bimestre: ')) while a > 10: a = int(input('Nota inválida! Digite o primeiro bimestre: ')) b = int(input('Digite o segundo bimestre: ')) while b > 10: b = int(input('Nota inválida! Digite o segundo bimestre: ')) c = int(input('Digite o...
conjunto = {1, 2, 3, 4} print(type(conjunto)) print(conjunto) #Não se repete. São elementos únicos conjunto2 = {1, 2, 3, 4, 4, 2} print(conjunto2) # Adicionando conjunto.add(5) print(conjunto) # Eliminando conjunto.discard(2) print(conjunto)
#Descobrindo os números primos em um range a = int(input('Digite um número para ver os números primos: ')) for num in range(a): div = 0 for x in range(1, num + 1): resto = num % x if resto == 0: div += 1 if div == 2: print(num)
def make_bread(arg1, arg2, arg3): if arg1 == 'water' and arg2 == 'flour' and arg3 == 'eggs': return 'dough' else: return 'not dough' # Test for bake def bake(arg1): if arg1 == 'dough': return 'brioche' else: return 'not brioche' def run_factory(arg1, arg2, arg3): re...
import math def print_hi(message): print(f'Hi, {message}') def factorial(number): return math.factorial(number) def log(number): return math.log(number) def sqrt(number): return math.sqrt(number) if __name__ == '__main__': print_hi('Hi, Welcome to simple math helper') print('What would...
# -*- coding: utf-8 -*- import csv import os import networkx as nx import time import zipfile import shutil # Function that read a csv file and return a list with a dict for each row def csvToDictList(filename): with open(filename, 'r') as csvfile: csvdata = csv.DictReader(csvfile, delimiter=';') ...
#!/usr/bin/python import sys from datetime import datetime arguments=sys.argv[1:] if "-f" in arguments: format=sys.argv[2] else: format="%d/%m/%Y" arg2=sys.argv[len(sys.argv)-1] if len(sys.argv) in [3,5]: arg1=sys.argv[len(sys.argv)-2] else: currentt=datetime.now() arg1=currentt.strftime(format) def countDays(f...
import pandas as pd # Catch raw song data as music variable music = pd.read_csv("featuresdf.csv") # Get Ed Sheeran songs by looping over list comprehension for track in (song for artist, song in zip(music.artists, music.name) if 'Sheeran' in artist): print(track) # High energy tracks (>0.8) def get_energy(cuttof...
class Heap: def __init__(self): self.storage = [] def insert(self, value): # pass self.storage.append(value) self._bubble_up(len(self.storage) - 1) def delete(self): pass def get_max(self): # pass print('self.storage:', self.storage) ret...
""" Project Euler Problem 5: https://projecteuler.net/problem=5 Smallest multiple What is the smallest positive number that is _evenly divisible_ by all of the numbers from 1 to 20? """ def solution(n: int = 7) -> int: try: n = int(n) except (TypeError, ValueError): raise TypeError("Paramete...
import unittest from app.models import Pitch class PitchModelTest(unittest.TestCase): def setUp(self): self.new_pitch = Pitch(id = 1, title = 'hilarious', pitch_content = 'I saw you in my dreams and i dint wanna wake up', category = 'Pickup Line', upvote = 1, downvote = 1, author = 'james') def test_...
# You are required to write a program to sort the (name, age, score) tuples by ascending order where name is string, # age and height are numbers. The tuples are input by console. The sort criteria is: # 1: Sort based on name; 2: Then sort based on age; 3: Then sort by score. # The priority is the same as name > age > ...
# ############################################### # Question 1 # A program which will find all such numbers which are divisible by 7 but are not a multiple of 5, # between 2000 and 3200 (both included). from random import shuffle import random import math import re from math import pi from functools import l...
# Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. # The overall run time complexity should be O(log (m+n)). # Using binary search algorithm def findMedianSortedArrays(nums1, nums2): # Ensure that nums1 is the shorter array if len(nums1) > len(nu...
# With a given tuple(1,2,3,4,5,6,7,8,9,10), write a program to print the first half # values in one line and the last half values in one line. tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) tup1 = tup[:5] tup2 = tup[5:] print(f"First half = {tup1} \n Second half = {tup2}")
# QUESTION # Have you heard of the fibonacci sequence? It is defined by f0=0, f1=1 and fn=fn-1 + fn-2 for n>=2. # This question is about a similar sequence, called gibonacci sequence. It is defined by g0 = x, g1 = y and gn = gn-1 - gn-2 for n >= 2. # Different possible starting values of the gibonacci sequence may lead...
# Write a program which can map() and filter() to make a list whose elements are square of # even number in [1,2,3,4,5,6,7,8,9,10]. even_filtered = [even for even in filter( lambda u: u % 2 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])] squared_even = [square for square in map(lambda m: m**2, even_filtered)]
# Given a signed 32-bit integer x, return x with its digits reversed. # If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. # Assume the environment does not allow you to store 64-bit integers (signed or unsigned). def reverse_integer(x): # Check if x is w...
# Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). # Example: If the following n is given as input to the program: 5 # Then, the output of the program should be: 3.55 def formula(n): result = 0 if n > 0: list_n = [i for i in range(1, n+2)] for num in list...
# Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. # You must implement a solution with a linear runtime complexity and use only constant extra space. # SOLUTION def singleNumber(nums): result = 0 for num in nums: result ^= num return resul...
""" ZADANIE 4.2 Rozwiązania zadań 3.5 i 3.6 z poprzedniego zestawu zapisać w postaci funkcji, które zwracają pełny string przez return. """ print("---Zadanie 4.2---") #3.5 def make_linijka(length): pattern = "|...." linear = ['', '0'] linijka = '' for i in range(length): linear[0] += pattern...
""" ZADANIE 2.10 Mamy dany napis wielowierszowy line. Podać sposób obliczenia liczby wyrazów w napisie. Przez wyraz rozumiemy ciąg "czarnych" znaków, oddzielony od innych wyrazów białymi znakami (spacja, tabulacja, newline). """ print("---Zad 2.10---") line = """jeden dwa trzy cztery piec szesc siedem osiem dziew...
import requests, time print("\n---> This is a Site Connectivity Checker <---\n") print("Input your URL in the following format 'http://www.google.com'") url = "http://google.com" diff = 1 count = 1 flag = 1 def initialize(): url = input("Enter a URL to check: ") diff = input(f"Ping {url} on an interval of (se...
from algorithms.AbstractGenetic import AbstractGeneticAlgorithm import numpy as np import copy from solution.Solution import Solution import pandas as pd import math class FireflyAlgorithm(AbstractGeneticAlgorithm): def __init__( self, absorption_coefficient=1, attractivness_coefficient=1, alpha=1, **kwds...
import psycopg2 import pandas as pd import tabulate as tb import csv import os fileName = 'test.csv' hostName = input('Enter host name :') portNumber = input('Enter port number :') databaseName = input('Enter database Name :') userName = input('Enter user name :') passwordOfDb = input('Enter password :') tableName = i...
file = input("") tokenCount = 0 types = set([]) #f = open(file, "r") #for line in f: with open(file, 'rb') as f: contents = f.read() content = contents.split() for tokens in content: tokens.lower() if tokens.isalpha: tokenCount += 1 types.add(tokens) ratio = tokenCount/len(types) print("File: " + file + "\...
#!/usr/bin/env python3 """Count the number of times each anchor in the given YAML file is used.""" import argparse import re from pathlib import Path def main(file: str): contents = Path(file).read_text() counter = {} for anchor in re.findall(r'(?<=&)[\w-]+', contents): if anchor in counter: ...
from random import randrange from collections import deque class Game(object): def __init__(self): self.rows = 9 self.columns = 9 self.density = 20 def initialize(self): self.board = Board(self.rows, self.columns, self.density) self.game_status = 'RUNNING' def sta...
##python code to clean and tokenize a file from __future__ import print_function import string import re,sys,os,codecs from unicodedata import normalize from mosestokenizer import * # load document into memory def load_doc(filename): # open the file as read only file = codecs.open(filename, 'r', encoding='utf-8') # ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ANFIS in torch: the ANFIS layers @author: James Power <james.power@mu.ie> Apr 12 18:13:10 2019 Acknowledgement: twmeggs' implementation of ANFIS in Python was very useful in understanding how the ANFIS structures could be interpreted: https://gi...
""" ConfigFile.py Created on: Feb 8, 2016 Author: Lee """ def basic_parse(file_name): """ Parses a config file with format: <Field Name 0>: <Value 0> <Field Name 1>: <Value 1> . . . <Field Name n>: <Value n> Inputs: config file name Outputs: a dictionary consisting...
# use input para guardar o nome digitado pelo usuário # coloque a variável que você criou antes no local correto abaixo: print("Olá", ,"!") # use input para perguntar a idade do usuario # use int para converter a idade digitada em número idade = int(idade) # coloque a variável com a idade no local correto...
## 1 - Criar expressões para as seguintes operações: # a) Somar sua idade e 10: # b) Calcular o dobro de 35: # c) Diferença da sua idade com a de um(a) colega: # d) Somar o dobro da sua idade com a metade da idade de um(a) colega: ## 2 - Usar parênteses, se necessário, para que as expressões abaixo faç...
##Practical 5 ##Question 1 ##try: ## dataFile = open('Data/precipitations-europe.txt') ##except IOError as err: ## print ('The following error occurred:',err) ##else: ## data = dataFile.readlines() ## dataFile.close() # we have read the full content of the file so we can close it ## minPrecipitation = []...
# Each order is represented by an "order id" (an integer). # We have our lists of orders sorted numerically already, in lists. Write a function to merge our lists of orders into one sorted list. # def merge_list(my_list, alice_list): # len_merged_list = len(my_list)+len(alice_list) # index_my_list = 0 # index_alic...
#!usr/bin/env python # Created by: Cameron Teed # Created On: September 2019 # This program adds two numbers together def main(): # This program adds two numbers together # Input first_number = int(input("enter the first number: ")) second_number = int(input("enter the second number: ")) # Proc...
class Solution: def isRectangleOverlap(self, rec1, rec2) -> bool: """ 矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。 如果相交的面积为正,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。 给出两个矩形,判断它们是否重叠并返回结果。 """ # 长和宽的坐标都分别相交 x1,y1,x2,y2=rec1 x3,y3,x4,y4=re...
class ListNode(): def __init__(self, node=None): self.val = node self.next = None class Solution(object): def hasCycle(self, head): """ 给定一个链表,判断链表中是否有环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 """ if not head: ...
class Solution: def containsNearbyDuplicate(self, nums, k): """ Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 给定一个整数数组和一个整数 k,判断数组中是否存在两个不...
class Solution(object): def findComplement(self, num): """ 给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。 注意: 给定的整数保证在32位带符号整数的范围内。 你可以假定二进制数不包含前导零位。 :type num: int :rtype: int """ i = 1 while i <= num: i = i << 1 return (i-1) ^ num...
class TreeNode: def __init__(self,x): self.val = x self.left = None self.right = None class Tree: def __init__(self): self.root = None def add(self,item): node = TreeNode(item) if self.root is None: self.root = node return ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def __init__(self): self.res = [] def leafSimilar(self, root1, root2): """ 请考虑一颗二叉树上所有的叶子,这些叶...
class TreeNode: def __init__(self,x): self.val = x self.left = None self.right = None class Tree: def __init__(self): self.root = None def add(self,item): node = TreeNode(item) if self.root is None: self.root = node return ...
class Solution(object): def hasAlternatingBits(self, n): """ 给定一个正整数,检查他是否为交替位二进制数: 换句话说,就是他的二进制数相邻的两个位数永不相等。 :type n: int :rtype: bool """ t = n ^ (n>>1) return (t&(t+1))==0 class Solution2(object): def hasAlternatingBits(self, n): return...
class TreeNode: def __init__(self,x): self.val = x self.left = None self.right = None class Tree: def __init__(self): self.root = None def add(self,item): node = TreeNode(item) if self.root is None: self.root = node return ...
class Solution: def findPairs(self, nums, k): """ Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. ...
class Solution: def largestPerimeter(self, A) -> int: """ 给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、面积不为零的三角形的最大周长。 如果不能形成任何面积不为零的三角形,返回 0。 """ A = sorted(A) while len(A)>=3: if A[-3]+A[-2] > A[-1]: return A[-1]+A[-2]+A[-3] else: ...
# class Room: # def __init__(self, name, description, exits): # self.name = name # self.description = description # self.exits = exits # def get_description(self): # return f"Name: {self.name}\nDescription: {self.description}\nExits: {self.exits}\n" # room_1 = Room("Main Hall"...
def main(): contacts = [] continue_ = True while continue_: choice = int(input("\nContacts\ \n========\ \n1. View Contacts\ \n2. Add new contact\ \n3. Search\ \n4. Update contact\ \n5. Delete Contact\ \n6. Quit\ \nEnter choice number\ ...
#coding utf-8 def backtracking(word): if(len(word) < 3): return for i in xrange(len(word)): new_word = word[:i] + word[i+1:] if(new_word not in set_words): set_words.add(new_word) backtracking(new_word) while True: try: global set_words set_words = set() word = raw_input() set_words.a...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' 只要当前序列中的'('多于')'即合法 def duang(left_n, right_n, max_n, base=''): if left_n == max_n: base += ')'*(max_n-right_n) return(base) if left_n > right_n: duang(left_n+1, right_n, max_n, base+'(') duang(left_n, right_n+1, max_n, base+')') ...
from tkinter import * import time class GameUI: # Variables rotationsAfterBoss = 0 # Initializing Object def __init__(self, bot): self.window = Tk() self.window.geometry("700x350") self.game_bot = bot self.run = False def startMenu(self): win = self.window...
# method that sums up all integers in any array; basically involves flattening a nested list def _flattenNestedList(inputlist): for item in inputlist: if not isinstance(item,(list,tuple)): yield item else: for subitem in _flattenNestedList(item): yield subite...
""" Solution for exercise 8.12 from Think Python. Author: Aliesha Garrett """ def rotate_word(s,i): """ 'Rotates' each letter in a word 'i' places. (Rotating a letter is shifting through the alphabet, wrapping around to the beginning again if necessary.) i: integer s: string """ word='' if ab...
"""This code creates a dragon curve. Author: Aliesha Garrett """ import math from swampy.TurtleWorld import * def dragon(t, length, n): """ dragon draws a dragon curve. t: A turtle. length: Length of the steps- should be a positive integer. n: The number of recursions to go through. Should be a positive inte...
import sqlite3 from sqlite3 import Error class UserDeviceDB: create_user_table = """ CREATE TABLE IF NOT EXISTS users ( email TEXT PRIMARY KEY, device_id INTEGER, topic_arn TEXT ); """ create_device_table = """ CREATE TAB...
class programs: def __init__(self,ai,ml,course,i,desig): self.ai = ai self.ml = ml print("course 1.) ml or 2.) ai") course = input() print(course) if (course == 'ml' ): print("mentor or student") desig = input() print(desig) if (desig == 'mentor'): ai = [] ai = in...
''' #! coding=utf-8 @Author: zmFeng @Created at: 2019-06-12 @Last Modified: 2019-06-12 8:26:56 am @Modified by: zmFeng expression builder ''' from utilz import triml class AbsResolver(object): ''' a class to resolve argument passed to it, this default one return any argument passed to it ''' ...
''' The solution follows the following approach: ->Pour from first bucket to second 1.Fill the first bucket and empty it into the second bucket. 2.If first bucket is empty fill it. 3.If the second bucket is full empty it. 4.Repeat steps 1,2,3 till either the first or second bucket contains the desired amou...
import math def fuel_double_checker(file): f = open(file, "r") fuel_total = 0 for line in f: fuel_module = math.floor(int(line)/3) - 2 fuel_total = fuel_total + fuel_module while (math.floor(fuel_module/3) > 0): fuel_module = math.floor(fuel_module/3) - 2 if...
''' Created on 17 ene. 2019 * Contruir un objeto Fraccion pasándole al constructor el numerador y el denominador. * Obtener la fracciónn. * Obtener y modificar numerador y denominador. No se puede dividir por cero. * Obtener resultado de la fracción(número real). * Multiplicar la fracción por un número. * M...
"""Doc string.""" from clean_up import clean_text_in from pprint import pprint from sys import argv import histogram import random def random_words(word_count, histogram): """Returns dict containing random words & number of times it was chosen.""" # Dict will hold random word and number of times that word wa...
#!/usr/bin/python """ Just count all the vowels and consonants """ def fun(string): """ something is missing. I can't get correct number of consonants in output I saw this game/trick in a video lecture in Python Bible, good series and modified it to make it a function so that it can be called again and ag...
class BST : def __init__(self, data) : self.data = data self.right = None self.left = None def set_data(self, data) : self.data = data def get_data(self) : return self.data def get_right(self) : return self.right def get_left(self) :...
from array import * array1 = array('i', [10,20,30,40,50]) array1.insert(2,90) array1.remove(30) print(array1.index(40)) array1[4]=300 for x in array1: print(x)
def mix_up(a, b): x=a[1] y=b[1] s=list(a) r=list(b) s[1]=y r[1]=x a=''.join(s) b=''.join(r) c=a a=b b=c return (a,b) print(mix_up("archit","sharma"))
# testing type modifications car = input("Enter car price: ") car = int(car) car += 5 print(car) house = int(input("Enter house price: ")) house -= 5 print(house) input("Press Enter to exit")
# A module for standard card deck class UsualCardSet: """Describes a standard card""" SUITS = ["Spades", "Hearts", "Diamonds", "Clubs"] RANKS = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] def __init__(self, suit=None, rank=None): self.suit = suit se...
# A module for a simple game class CardPlayer: """Describes a card player as object""" def __init__(self, name, score=0): self.name = name self.cards = [] self.score = score def __str__(self): rep = "\tName: " + self.name + "\n\tCards: " + ', '.join(map(str, self.cards)) ...
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ bit = [] flag = 1 if x > 0 else -1 x = abs(x) result = 0 while x > 0: result = result * 10 + x % 10 x = x / 10 # big than 32-bit sing...
def comma(s1): for f in range(len(s1)): if s1[f] not in "0123456789,": raise Exception("Invalid input. Your input contains characters other than numbers and commas.") else: if s1[f]=="," and s1[f+1]==",": raise Exception("Invalid input. Your input contains 2 o...
import requests APPID = "b4534e0524a27721f663d669f5581780" URL_BASE = "http://api.openweathermap.org/data/2.5/" def current_weather(lat: float, lon: float,units: str = "metric", appid: str = APPID) -> dict: print(locals(), end='\n=========\n') res = requests.get(URL_BASE + "weather", params=locals()).json() ...
import pandas as pd FILENAME = "salary.csv" def load_data(): """ This function read the csv file and looks for a place to divide the data set. Return the tuple with <numpy.ndarray> objects: - worked years - salary brutto - worked years to prediction ...
def FLOYD_WARSHALL(weight): #Setting n to be the keys of the dictionary n = weight.keys() print weight #Checks the amount of vertices if len(n) > 100: print 'The maximum number of vertices of the directed graph is 100 and yours is', len(n) else: for m in n: print '' ...
a = int(input("Enter a: ")) b = int(input("Enter b: ")) c = int(input("Enter c: ")) d = b ** 2 - (4 * a * c) x1 = (-b - d ** 0.5) / (2 * a) x2 = (-b + d ** 0.5) / (2 * a) print(" 답은: ", x1, "and", x2)
import re import encodings months = ('January','February','March','April','May','June',\ 'July','August','September','October','November',' December') print(months) mystr="ddd" cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester'] cats.append("pippo") cats.count(4) print(cats) dict = {'Andrew Parson':8806336, \...
x=int(input()) y=0 while x>0: x=x // 10 y=y+1 print (y)
import sqlite3 import json import csv from datetime import datetime db_name = "test" sql_transaction = [] connection = sqlite3.connect('{}.db'.format(db_name)) c = connection.cursor() def create_table(): c.execute("""CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, first_name TEXT, last_name TEXT, ...
# Binomial Experiment # A binomial experiment (or Bernoulli trial) is a statistical experiment that has the following properties: # 1. The experiment consists of n repeated trials. # 2. The trials are independent. # 3. The outcome of each trial is either success (s) or failure (f). # Bernoulli Random Variable and Dist...
from math import erf cdf = lambda x: .5 + .5 * erf((x - mu)/2 ** .5/sigma) print(round(cdf(x1), 3)) print(round(cdf(x3) - cdf(x2), 3)) # Create a function for integration # Calculate the area underneath a curve for a finite interval # One method to compute integrals approximately, that a computer can actually handle, i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 19 15:13:44 2020 @author: fiona """ # input() function # x = input("Enter your name:") # print("Hello, " + x) # Day 0: Mean, Median, and Mode n = int(input()) # change a string to an integer nums = [int(i) for i in input().split(' ')] # Mean mean...
import math import os import random import re import sys from collections import Counter # Complete the makeAnagram function below. def makeAnagram(a, b): # .subtract(): Elements are subtracted from an iterable or from another mapping (or counter) dict_a = Counter(a) dict_b = Counter(b) dict_a.subtract...
# From: https://stackoverflow.com/questions/40330623/keep-on-halving-by-integer-division-until-x-1/40330685 def keep_dividing(x): num = x # temp variable count = 0 # number of times divided while num > 1: num //= 2 print(num) count += 1 print("number of times divided = ",...
class Solution: def isPowerOfTwo(self, n: int) -> bool: if n == 1 or n == 2: return True base = 2 while base < n: base = base * 2 if n == base: return True return False
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: even_array = [] odd_array = [] for num in A: if num % 2 == 0: even_array.append(num) else: odd_array.append(num) even_array.extend(odd_array) return...
from itertools import permutations import enchant d = enchant.Dict("en_US") chars = input("Enter Space Separated Letters\n").split() anagrams = list(permutations(chars,len(chars))) file = open("All-Anagrams.txt","w") mfile = open("Meaningful Anagrams.txt","w") for i in range(len(anagrams)): anagrams[i] = "".join(k ...
PreOrderS = "" InOrderS = "" class TreeNode: def __init__(self,key): self.key = key self.left = None self.right = None self.p = None def __str__(self): return str(self.key) def PreOrder(n): PreOrderS = "" PreOrderS+=n.data def PreOrderHelper(n): PreOrderS+=n.data if (n.left == None): PreOrderS+="0...
""" Working with MongoDB vs PostgreSql: Perhaps the most obvious difference is that the commands/syntax are slightly different between the two. SQL in general is more straight forward and intuitive than MongoDB. I also do like how we could test out queries in ElephantSQL and DB Browser. This is helpful especially sinc...
#Joseph Harrison 2020 #find prime-power factorisations import gcdbez def prime_pow_fact(n): ppf = {} #divide n by 2 until it 2 doesn't divide it anymore while n % 2 == 0: if 2 not in ppf: ppf[2] = 1 else: ppf[2] += 1 n //= 2 #now try all odd integers k = 3 while n != 1 and k <= n: if n % k == 0 and...
class Point(object): def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return '(%d, %d)' % (self.x, self.y) def __add__(self, other): added_x = self.x + other.x added_y = self.y + other.y combined = Point(added_x, added_y) return...
#Getting the alphabet to ease things up from string import ascii_uppercase def __main__ (): key = input('Enter the key: ') key = key.replace(' ', '') key = key.upper() t = int(input('Enter T parameter: ')) text = input('Enter the text: ') text = text.replace(' ', '') text = text.upper() ...
# write your code here # print("Enter letters:") xcount = 0 ocount = 0 def printTicTacToe(): global i, j xcount = 0 ocount = 0 print("---------") for i in ticTacToeMatrix: print("|", end=" ") for j in i: if j == "O": ocount += 1 elif j == "X...
""" String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3, If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume t...
""" Stack Min: How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time. """ class MinStack: def __init__(self, data=[]): self.data = data self.min = min(data, default=None) def __str__(self): retur...