text
stringlengths
37
1.41M
number = raw_input("Type a number --> ") print "If you add all the integers between 1 to", number, "you get.."
while True: prompt = raw_input ("Type the word Girls Who Code\n--->") if prompt == "Girls Who Code": print "Good Job!" break if prompt != "Girls Who Code": print "That's not right try something else"
colors = ["red", "yellow", "green", "blue"] i = 0 while i < len(colors): print "When I was %d, my favorite color was %s" % (i, colors[i]) i = i + 1
while True: print "Type in a month's and learn how many days it has." month = raw_input() if month.lower() == "january": print "31" elif month.lower() == "february": print "28" elif month.lower() == "march": print "31" elif month.lower() == "april": print "30" ...
"""Func""" def func(): """Call center""" price = int(input()) minutes = int(input()) second = int(input()) if price == 0: print("free") else: if second > 30: minutes += 1 second = 0 if minutes*60 <= 120: print("free") else: ...
"""Func""" def checkremoved(removedscore): """Check for real score""" if removedscore < -10: realscore = 0 else: realscore = 10 + removedscore if removedscore == 0: removedscore = "-0" else: removedscore = str(removedscore) return [removedscore, realscore] def ...
"""Func""" def func(): """Find max""" inp1 = float(input()) inp2 = float(input()) inp3 = float(input()) inp4 = float(input()) inp5 = float(input()) inp6 = float(input()) inp7 = float(input()) inp8 = float(input()) inp9 = float(input()) inp10 = float(input()) def greater(n...
"""Func""" def checkprime(number): """Check for prime""" if number <= 3: return False if number == 1 else True if number%2 == 0 or number%3 == 0: return False i = 5 while i * i <= number: if number % i == 0 or number % (i + 2) == 0: return False i = i + 6...
"""Func""" def func(): """Pork maker""" mhcount = 0 phcount = 0 shcount = 0 whcount = 0 wrongcount = 0 #err totalcount = 0 while True: ingredient = input().upper() if ingredient == "MH": mhcount += 1 elif ingredient == "PH": phcount += 1 ...
"""Func""" def func(): """Icecream""" me_x = int(input()) me_y = int(input()) icea_x = int(input()) icea_y = int(input()) iceb_x = int(input()) iceb_y = int(input()) def distance(ice_x, ice_y): """Find distance""" return (pow(me_x-ice_x, 2) + pow(me_y-ice_y, 2))**0.5 ...
"""Func""" def func(): """Find sum less than 100""" def check(number): """Checker""" if number > 100: return 0 else: return number number1 = check(int(input())) number2 = check(int(input())) number3 = check(int(input())) number4 = check(int(input(...
"""Func""" def func(): """Guess""" wantnumber = int(input()) times = int(input()) i = 0 while i < times: guess = int(input()) if guess == wantnumber: print("Yes! It is %d." %guess) break if i == times-1: print("No more chances. You lose.")...
"""Func""" def func(): """Calcualte func""" vala = int(input()) valb = int(input()) # != 0 valc = int(input()) # != 0 vald = int(input()) print("%.2f" %(((vala/valc) + vald)/valb)) func()
"""Func""" def func(): """Promotion""" ppamount = int(input()) priceperperson = float(input()) discount = int(input()) def method1(priceperperson, ppamount, discount): """method 1""" if ppamount >= 3: return (priceperperson*ppamount) * ((100-discount)/100) else:...
"""Func""" def func(): """Dota2 kebab""" price = int(input()) amount = int(input()) feedb = input() if feedb == "This kebab is very good": print("%.2f" %((0.7*price) * amount)) elif feedb == "This is not good not bad": print("%.2f" %((0.95*price) * amount)) elif feedb == "Th...
"""Func""" def func(): """Matrix V.3""" rowcol = list(map(int, input().split(" "))) fullmatrix = [] for i in range(rowcol[0]): matrix1 = list(map(int, input().replace("[", "").replace("]", "").split(", "))) fullmatrix.append(matrix1) newmatrix = [] for i in range(rowcol[1]): ...
"""Func""" def func(): """Time format func""" second = int(input()) day = second//(24*60*60) hour = (second//3600)%24 minute = (second//60)%60 sec = second%60 print("%02d:%02d:%02d:%02d" %(int(day), int(hour), int(minute), int(sec))) func()
"""Func""" def func(): """Wendy""" otheringredient = False buncheck = "" i = 0 while True: ingredient = input() i += 1 if ingredient == "Vegetables": print("We have to cancel your order! Get out!!") break elif ingredient == "Cheese" or ingredi...
"""Func""" def func(): """X burner""" itemsneed = ["X-gloves", "Leon's tail", "Bullet", "Contact lens", "Ring", "Reborn", "Tsuna"] while True: items = input() if items.lower() == "end": break for item in items.split(","): if item.strip() in itemsneed: ...
"""Func""" def check1(password): """check 1""" score = 0 if password.isdigit(): # print("isdigit") score += 50 if password.isalpha(): # print("isalphab") score += 30 if password.islower() and password.isalpha(): # print("islower") score += 100 eli...
def do_plus(x,y): if (type (x)== type(1)) and (type (y)== type(1)): print(type (x)) print(type (y)) return x+y else: return str(x)+str(y)
# https://www.codewars.com/kata/roboscript-number-1-implement-syntax-highlighting import re import codewars_test as Test def highlight(code): ret = code ret = re.sub(r"(F+)", '<span style="color: pink">\\1</span>', ret) ret = re.sub(r"(L+)", '<span style="color: red">\\1</span>', ret) ret = re.sub(r"...
# defining a list my_list = ('2', '5', [1,2]) print(my_list) #te dice que methods pueden usarse dentro de la variable print(dir(my_list)) # index, comienza de 0 a contar print(my_list[1]) #index una lista dentro de otra lista print(my_list[2][1]) #para ver la longitud de la lista print(len(my_list)) #print(my_list[len(...
class Persona: def __init__(self,nombre,apellidos,edad,ocupacion,turno,sexo): self.nombre = nombre self. apellidos = apellidos self.edad = edad self.ocupacion = ocupacion self.turno = turno self.sexo = sexo class Alumno(Persona): def __init__(self,nombre,ape...
#Wilfred Githuka #Githuka.com #Saturday 16 December 2017 #Udacity Self Driving Car Nanodegree #Project1-Finding Lane Lines on The Road #Color Selection Code Example import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np image = mpimg.imread ('test.jpg') print ('This image is : ',type(imag...
# How many passwords are valid according to their policies? def read_input(file_loc): with open(file_loc, "r") as f: values = f.read().split('\n') values = [i.split(': ') for i in values] return values # for part 1 def pw_is_valid(rule_min, rule_max, rule_char, pw): count = pw.count(rule_char)...
# What is the ID of the earliest bus you can take to the airport # multiplied by the number of minutes you'll need to wait for that bus? import math def read_input(file_loc): with open(file_loc, "r") as f: return f.read().split("\n") notes = read_input("../Inputs/day13.txt") earliest_time = int(notes[0])...
"""Utility functions.""" from matplotlib import pyplot as plt import numpy as np def share_fig_ax(fig=None, ax=None, numax=1, sharex=False, sharey=False): """Reurns the given figure and/or axis if given one. If they are None, creates a new fig/ax. Parameters ---------- fig : `matplotlib.figure.Figur...
""" Implements a simple Python iteration dillema """ import numpy as np def iterator(size, mult): arr = np.ndarray((size, size), dtype=np.float64) x = 0 it = 0 for ix in np.nditer(arr, op_flags=['readwrite']): ix[...] = x x += it * mult it += 1 return arr #myarr = iterator(...
from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age # a class method to create a # Person object by birth year. @classmethod def fromBirthYear(cls, name2, year): return cls(name2, date.today().yea...
File = open("Information.txt", "r") #print(File.read()) #print(File.readline()) data = File.readlines() for i in data: print(i)
#How to remove duplicate delecation from list ? a = ['ab', 'cd', 'ef', 'gh', 'ab', 'cd', 'ef', 'gh'] list = [] for i in a: if not i in list: list.append(i) print list
#Odd numbers for i in range(0,30): if i%2 == 1: print i for j in range(0,100): if j%2 == 1: print j print [k for k in range(0,20) if k%2 == 1]
def my_gen(n, m): yield n yield m print(m) n += 1 yield n n += 1 yield n n += 10 yield n b = iter(my_gen(1, 20)) print(next(b)) print(next(b)) print(next(b)) # Using for loop # for item in my_gen(1, 20): # print(item)
a = ["bangalore", "chennai", "pune"] for i in a: if i == 'chennai': continue else: if i == 'bangalore' or i == 'pune': print(i)
file = open('nums.txt', 'r') file_list = file.read().split(':') file.close() num_list = [] for i in file_list: num_list.append(int(i)) print('Have this list: \n' + str(num_list) + '\nStart sorting...') def quick_sort(l: list): if len(l) <= 1: return l bp = len(l) - 1 # l[bp], l[-1] = l[-1]...
num=int(input("enter a number:")) n=1 for i in range(0,num): for j in range(0,num-2): print(end=" ") for j in range(0,i+1): print(n,end=" ") n=n+1 print()
# getallenraden-SeanBooij # Input vragen voor het getal aan de gamemaster te_raden_getal = input("Welk getal wil je gebruiken?\n") # De loop om te vragen aan de nieuweling welk getal het is, met het maximaal aantal beurten. In dit geval 7. for i in range(0,7): ingevoerd_getal = input("Welk getal denk je dat he...
''' 输入一个链表,反转链表后,输出新链表的表头。 ''' # -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 头插法 19ms,5624k # 返回ListNode def ReverseList(self, pHead): # write code here if pHead == None: return ...
''' 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。 保证base和exponent不同时为0 ''' # -*- coding:utf-8 -*- class Solution: # 20ms,5692k def Power(self, base, exponent): # write code here return pow(base, exponent) # -*- coding:utf-8 -*- class Solution2:#22ms,5720k def Power(self...
''' 一个整型数组里除了两个数字之外,其他的数字都出现了两次。 请写程序找出这两个只出现一次的数字。 ''' # -*- coding:utf-8 -*- class Solution: # 28ms,5644k # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): # write code here count = 0 result = [] while len(array) > 0: a = array.pop() # ...
'''给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2];)''' # -*- coding:utf-8 -*- class Solution: def multiply(self, A): # write code here B = [] Alen = len(A) ...
''' 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老, 自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m, 让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物, 并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演, 并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢? (注:小朋友的编号是从0到n-1) 如果没有小朋友,请返回-1 '''...
def get_num(name: str) -> int: num = name.split('-')[1].lstrip('0') num = 0 if len(num) == 0 else int(num) return num def get_pod(name: str, k: int) -> int: num = name.split('-')[1].lstrip('0') num = 0 if len(num) == 0 else int(num) if name.startswith('h-'): pod = int(num / (k * k /...
s = input("Enter the String 1 : ") k = input("Enter the String 2 : ") k = k.lower() s = s.lower() count = 0 for i in s: if i not in k: count = 1 break else: count = 0 if count == 1: print("No") elif count == 0: print("Yes")
import numpy as np import matplotlib.pyplot as plt r = np.arange(0, 6.0, 0.01) ################################################ def function(r): theta = 4 * np.pi * r return theta ################################################### ax = plt.subplot(111, pola...
def isPrime(num): return False if num > 1: for i in range(2,num): if (num % i) == 0: return False else: return True return False
while True: try: print('Enter number:') #this prints a command for people to enter a number (works) number = int(input()) #this asks people to enter a number (works) except ValueError: print('please enter a numeric value.') else: break def collatz(): #define colla...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sortedArrayToBST(self, nums): """ Given an array where elements are sorted in ascending order, convert it to a heigh...
class Solution: def isHappy(self, n): """ Write an algorithm to determine if a number is "happy". Args: n(int): the given integer number Returns: A bool value(bool) """ history = [] while True: n = sum([int(d)**2 ...
# import all libraries from IPython.display import display, Image import numpy as np from keras.models import Sequential # initialize NN as a Sequence from keras.layers import Convolution2D # to deal with images from keras.layers import MaxPool2D # this will add pooling layers from keras.layers import Flatten # thi...
from collections import defaultdict class Furniture: '''An inventory item with a name, description, and price.''' def __init__(self, name, description, price): self.name = name self.description = description self.price = price def __str__(self): return self.name + '.' + '\n...
# Xander Eagle # January 6, 2020 # this program draws a target and adds up the total points based on where the user clicks import pygame class Target: def __init__(self, main_surface): self.main_surface = main_surface self.score = 0 def draw_target(self): # this functions draws the target...
#!/usr/bin/env python3 """ File: static_save.py Purpose: A decorator function to initialize a list of static variables to a None. Usage: In the python file, add the following line above the function definition which is to be decorated. @static_vars([<variable_list]) def targ...
""" This module implements several arithmetic and logical operations such that it maintains single-precision across variables and operations. It overloads double-precision floating variables into single-precision using numpy's float32 method, forcing them to stay in single-precision type. This avoids a possible butterf...
from itertools import permutations from itertools import combinations class Service(object): def sorted_key(self, word): chars = [c for c in word] chars.sort() return "".join(chars) def possiblepermutations(self,text): return [''.join(p) for p in permutations(text)] def...
a=int(input('Enter first number: ')) b=int(input('Enter second number: ')) if(a==b): print('Two numbers are equal') else: print('Two numbers are not equal')
import sys def appEnd(flag): if flag==1: file.close() sys.exit() path = "testfile.text" #input("path (e.x. testfile.text): ") #'testfile.text' procType = "symbols" #input("Select process method (words, sentences, symbols): ") minSymb = 20#int(input("Min count symbols: ")) maxSymb = 50#int(input("Max count sy...
# --- Define your functions below! --- from random import * def intro(): name = input("Hello! What's your name? ") print("Nice to meet you,", name) def is_valid_input(): while True: answer = input("What would you like to do? You can CHAT or PLAY rock, paper, scissors: ") valid_responses = ...
idade = int(input("Coloque sua idade: ")) if idade >= 18: print ("Maior") else: print ("Menor")
import requests def by_city(): city = input('Enter your city : ') url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid= your api key here &units=metric'.format(city) res = requests.get(url) data = res.json() show_data(data) def by_location(): res = requests.get('https://ipinfo.io...
from pynput.keyboard import Key, Controller import time import keyboard Keyboard = Controller() print(""" ██╗███╗ ██╗██████╗ ██╗ ██╗████████╗ ███████╗██████╗ █████╗ ███╗ ███╗███╗ ███╗███████╗██████╗ ██║████╗ ██║██╔══██╗██║ ██║╚══██╔══╝ ██╔════╝██╔══██╗██╔══██╗████╗ ████║████╗ ████║██╔════...
import pygame from pygame.locals import * class Control: def __init__(self): self.game_Play = True self.direction_controller = 'RIGHT' self.game_start = False self.pause = True self.game_start_counter = True #Простой контролер персонажа, в зависимости от нажатой кнопки...
#!/usr/bin/env python # Suggest a sexy Halloween costume idea import json import requests url = "http://whatthefuckshouldibeforhalloween.com/api.com?count=1" response = requests.get(url) json_data = json.loads(response.text) suggestion = json_data[0] print "%s %s" % (suggestion['prompt'], suggestion['costume'].uppe...
#Problème d'importation liée à un problème d'encodage, réglé par ces lignes #!/usr/bin/env python #-*- coding: utf-8 -*- #Fichier définissant la classe histoire from pickle import * #Module permettant la sauvegarde class Histoire: """Classe d'objet contenant la totalite d'une histoire: un attribut pour les p...
#!/usr/bin/env python3 class Ferry: def __init__(self, instructions, waypoint=False): self.x = 0 self.y = 0 self.facing = 0 self.waypoint_x = 10 self.waypoint_y = 1 for instruction in instructions: if not waypoint: self.move(instruction) ...
from collections import deque def materials_or_magics(m): if m: print("Materials left:", end=" ") print(*materials, sep=", ") materials = deque(int(n) for n in input().split() if int(n) != 0) magics = deque(int(n) for n in input().split() if int(n) != 0) gifts = { 150: ["Doll", 0], 250: ...
def get_matrix(matrix, n): position = [] for index in range(n): row = input() for col in range(n): if not row[col] == "-": matrix[index][col] = row[col] if row[col] == "P": position = [index, col] return matrix, position def n...
# function declaration def print_matrix(matrix): for row in range(0,len(matrix)): print(matrix[row]) def swap_row(matrix,row1,row2): for i in range(0,len(matrix)+1): temp=matrix[row1][i] matrix[row1][i]=matrix[row2][i] matrix[row2][i]=temp def scale_row(matrix,row,factor): ...
import threading import datetime from time import sleep class myThread(threading.Thread): def __init__(self, name): super().__init__() self.name = name def run(self): print (f"Starting {self.name}") threadLock.acquire(blocking=False, timeout=-1) print_date(self.name) ...
temperatura = int (print (input ("Digite uma temperatura: "))) print ("A temperatua em Fahrenheit é: " temperatura = (5/9) * (temperatura – 32))
'''Trabalho feito por david, gabriel rech e gabriel sgorla''' nota100 = 6 nota50 = 6 nota20 = 6 nota10 = 6 notas = 0 while True: saque = int(input("Digite quanto sacar: ")) if saque // 100 >= 1 and nota100 > 0: notas = saque // 100 saque = saque % 100 nota100 -= notas print("...
# Trabalhando com strings: # multstring: seja uma string s e um inteiro positivo n retorna uma # string com n cópias da string original multstring('Hi', 2) -> 'HiHi' print('Hi' * 2) #string_splosion: string_splosion('Code') -> 'CCoCodCode', # string_splosion('abc') -> 'aababc', string_splosion('ab') -> 'aab' palavr...
# Leia um número e imprima seu dobro​. num = int(input('Digite um número: ')) print('O dobro do número {} é {}.'.format(num, num * 2))
# Caixa Eletrônico # Desenvolva um programa que simule a entrega de notas quando um cliente # efetuar um saque em um caixa eletrônico. Os requisitos básicos são os seguintes:​ # - Entregar o menor número de notas;​ # - É possível sacar o valor solicitado com as notas disponíveis;​ # - Saldo do cliente infinito;​ # - Q...
'''exercicio feito por David, Gabriel Rech e Gabriel Sgorla''' import random lista1 = random.sample(range(0,20),5) lista2 = random.sample(range(0,20),10) lista3 = [] print(lista1) print("----------------------------------------------------------") print(lista2) print("--------------------------------------------------...
"""Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar: A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; A mensagem "Reprovado", se a média for menor do que sete; A mensagem "Aprovado com Distinção", se a média for i...
numero = int(input("Digite um numero para saber o dobro: ")) print("o dobro e: ", numero * 2)
val1 = int(input(print("Digite o primeiro valor: "))) val2 = int(input(print("Digite o segundo valor: "))) aux = 0 aux = val1 val1 = val2 val2 = aux print("Valor 1: ",val1," e valor 2: ",val2)
num = int (print (input ("Digite um número: "))) print ("O dobro do número é: "num*2)
# expresiones regulares (search, findall, split, sub) texto = "Hola, mi nombre es camila" import re resultado = re.search("camila$", texto) # devuelve match si encuentra camila$ busca si hay una frase que acabe en camila resultado = re.search("^Hola", texto) #^empieza con esa palaba en este caso hola (es sensible a m...
class Node(): def __init__(self, data, next=None): self.data = data self.next = next class Stack(): def __init__(self, head=None): self.head = head def isEmpty(self): if self.head == None: return True else: return False def push(self, data): if self.head == None: self.head = Node(data) els...
def reverse_array(arr): if len(arr) == 0: return start = 0 end = len(arr)-1 while start <= end: swap(arr, start, end) start += 1 end -= 1 return arr def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp return arr print(reverse_array([1,2,3,4,5,6]))
def find_min(arr): low = 0 high = len(arr)-1 right_pivot = arr[len(arr)-1] while low<=high: mid = low+(high-low)//2 if (arr[mid]<=right_pivot) and (mid==0 or arr[mid-1] > arr[mid]): return mid elif arr[mid] > right_pivot: low = mid+1 else: high = mid-1 return -1 print(find_min([7,8,1,2,3,4,5,6]))
def sort_subarray(arr): minimum = 0 maximum = float("inf") if len(arr) == 0: return 0 #Find Dip for start in range(0, len(arr)): if arr[start+1] > arr[start]: break if start == len(arr)-1: return #Find rise for end in range(len(arr)-1, 0, -1): if arr[end-1] > arr[end]: break for k in range(sta...
mnemonics_dict = { 0:[], 1:[], 2:["a","b","c"], 3:["d","e","f"], 4:["g","h","i"], 5:["j","k","l"], 6:["m","n","o"], 7:["p","q","r","s"], 8:["t","u","v"], 9:["w","x","y","z"], } def mnemonics(arr, buff, next_index, buff_index): #termination case if buff_index==len(buff) or next_index==len(arr): print(buff...
def print_combination(a, buff, start_index, buff_index): #terminatio case if buff_index==len(buff): print(buff) return if start_index==len(a): return for i in range(start_index, len(a)): buff[buff_index] = a[i] print_combination(a, buff, i+1, buff_index+1) print_combination([1,2,3,4,5,6], [0,0,0], 0, 0)
def reverse_array(arr): if len(arr) == 0 or arr==None: return -1 start=0 end = len(arr)-1 while start<=end: swap(arr, start, end) start += 1 end -= 1 return arr def swap(arr, start, end): temp = arr[start] arr[start] = arr[end] arr[end] = temp return arr print(reverse_array([1,2,3,4,5]))
def min_path_sum(arr): m = len(arr) n = len(arr[0]) for i in range(1, m): arr[i][0] += arr[i-1][0] for j in range(1, n): arr[0][j] += arr[0][j-1] for i in range(1, m): for j in range(1, n): arr[i][j] += min(arr[i-1][j] , arr[i][j-1]) return arr[-1][-1] print(min_path_sum([[1,3,1],[1,5,1],[4,2,1]])) p...
def hascycle(l): slow = l.head fast = l.head while fast is not None: fast = fast.get_next() if fast==slow: return True if fast is not None: fast = fast.get_next() if fast==slow: return True slow = slow.get_next() return False class Node: def __init__(self, data, next=None): self.data = data...
def countigous_subarray_sort(arr): if len(arr)==0 or arr==None: return -1 for start in range(0, len(arr)): if arr[start]>arr[start+1]: break if start == len(arr): return -1 for end in range(len(arr)-1, -1, -1): if arr[end-1] < arr[end]: break min_val = float("inf") max_val = float("-inf") for ...
def binary_search_cyclic(a): low = 0 high = len(a)-1 right = a[len(a)-1] while(low <=high): mid = low+(high-low)//2 if (a[mid] <= right) and (mid==0 or a[mid-1]>a[mid]): return mid elif a[mid] > right: low = mid+1 else: high = mid-1 return -1 print(binary_search_cyclic([4,5,6,1,2,3]))
def print_permutation(arr, k): if len(arr)==0 or arr==None or k==None: return isinBuffer = [False]*len(arr) buff = [0]*k print_permutation_helper(arr, buff, 0, isinBuffer) def print_permutation_helper(arr, buff, buffer_index, isinBuffer): #termination case if buffer_index == len(buff): print(buff[:buffer_in...
class StackAsQueue: def __init__(self): self.s1 = Stack() self.s2 = Stack() def flushtos2(self): while not self.s1.isEmpty(): self.s2.push(self.s1.pop()) def enqueue(self, a): self.s1.push(a) def dequeue(self): if self.s2.isEmpty(): self.flushtos2() if self.s2.isEmpty(): raise("s2 is empty"...
def longest_palindrome(s): if len(s)%2==0: val = check_even_palindrome(s) else: val = check_odd_palindrome(s) return val def check_odd_palindrome(s): longest = 1 for i in range(len(s)): offset = 0 while isvalid(s[i], i-1-offset) and isvalid(s[i], i+1+offset) and (s[i-1-offset]==s[i+1+offset]): offset +...
class Node: def __init__(self, data, next=None): self.data = data self.next = next def get_data(self): return self.data def set_data(self, data): self.data = data def get_next(self): return self.next def set_next(self, node): self.next = node class LinkedList(): def __init__(self, head=None, tail...
def isBalanced(root): if root==None: return 0 rightH = isBalanced(root.right) leftH = isBalanced(root.left) if rightH==-1 and leftH==-1: return -1 if abs(rightH)-abs(leftH) > 1: return -1 return 1+max(rightH, leftH) def is
def square_root(num): low = 0 high = num//2 while low<=high: mid = low + (high-low)//2 if mid*mid > num: high = mid-1 elif mid*mid < num: if (mid+1)*(mid+1) > num: return mid low = mid + 1 else: return mid return -1 print(square_root(36))
def prime_num(n): l1=[2] for i in range(3,10,2): l1.append(i) for i in l1: if n%i==0: return False return True def main(): n=eval(input("Enter the number:")) result=prime_num(n) print (result) main()
''' PROBLEM MAKING_ANAGRAMS Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact fre...