text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- """ Created on Mon May 4 09:47:46 2015 @author: liran """ class A: @staticmethod def st(): print "static" def __init__(self,num): self.__num = num print "A" def f1(self): print self.__num class B(A): def __init__(self,num,size): A._...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed May 17 17:20:38 2017 @author: parallels """ # Using the generator pattern (an iterable) class firstn(object): def __init__(self, n): self.n = n self.num, self.nums = 0, [] def __iter__(self): #self.num, self.nums = 0, [...
# Python 2 version # Code for reading in the date */ date = raw_input("Please enter date (DD/MM/YYYY): ") d,m,y = date.split('/') d = int(d) m = int(m) y = int(y) """ Add Your Code Here: to adjust the values of d, m and y under certain circumstances d contains the day m co...
#!/usr/bin/python Belgium = 'Belgium,10445852,Brussels,737966,Europe,1830,Euro,Catholicism,Dutch,French,German' items = Belgium.split(',') print '-' * len(Belgium) print ':'.join(items) #print items[1] + items[3] print int(items[1]) + int(items[3]) print '-' * len(Belgium) """Well I have this large quanti...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri May 12 11:49:31 2017 @author: parallels """ # #class First(object): # def __init__(self): # print "first" # def ff1(self): # return 1 # #class Second(First): # def __init__(self): # super(First, self).__init__() # pr...
# -*- coding: utf-8 -*- class Rectangle: def __init__(self,width,height): self.__width = width self.__height = height def __PrintHeader(self): print("******************************************") def Print(self): self.__PrintHeader() print("Recangle Width:" + str(se...
class Invoker(object): def __init__(self): self._subscribers = [] def __add__(self,subscriber): self._subscribers.append(subscriber) return self def __sub__(self,subscriber): if(subscriber in self._subscribers): self._subscribers.remove(subscriber) re...
from Country import Country countries = [] # Question 1a, implement a constructor for line in open('country.txt') : countries.append(Country(line)) # Question 1b, implement a printit method for country in countries: country.printit() # Question 1c, implement string overloading pri...
''' To create a program to check whether two words/sentences are anagrams of each other or not. ''' def anagram_check(s1,s2): s1 = "".join(s1.lower().split()) s2 = "".join(s2.lower().split()) if len(s1) != len(s2): return False d1 = {} d2 = {} for i in s1: try: d...
''' Alternate implementation of BFS. ''' graph = { 'A' : set(['B','C']), 'B' : set(['A','D','E']), 'C' : set(['A','F']), 'D' : set(['B']), 'E' : set(['B','F']), 'F' : set(['C','E']) } def bfs(graph,start): visited = set() queue = [start] while q...
''' Given an array of values and a target sum, check wether the given sum is possible to be made from the subset of the given elements. For example: arr = [1,3,5] tar = 4 ANSWER => True tar = 2 ANSWER => False ''' from numpy import array def subsetsum(arr,val): ''' arr : <int> array ...
''' Given a string, find all the permutations of the string using recursion. ''' def permutation(s): out = [] if len(s) <=1 : out = [s] else: for i,letter in enumerate(s): for perm in permutation(s[:i]+s[i+1:]): out += [letter+perm] return out ...
''' Given an array of elements, count the number of subarrays with a given sum. For example: ''' def countSubarraySum(arr,k): values = dict() values[0] = 1 currsum = 0 count = 0 for i in arr: currsum += i if currsum - k in values: count += values[currsum-k] i...
''' Given an array of integer elements, form 2 subsets such that the difference between those two array is minimum. For example: arr = [1,6,11,5] subsets = [1,11],[5,6] diff = 1 => minimum difference ''' from numpy import array ''' The main approach to this problem is that, we have to minimize s1 - s...
''' Write a function to reverse a Linked List in place. The function will take in the head of the list as input and return the new head of the list. ''' class Node: def __init__(self,value): self.value = value self.nextnode = None # Not Inplace def reverse(head): placeholder = head tem...
# Name Jesse Coyle # Date 1/18/2020 # File tile.py # Desc definitions for tiles class Terrain: def __init__(self, id, name, ascii, energy): # Note(Jesse): member integer that identifies this specific Obstacle # 0 _cannot be valid_ self.id = id # Research(Jesse): We might not need the id self.name...
# a tuple that stores the months of the year, from that tuple # create another tuple with just the summer months (May, June, July), # print out the summer months one at a time. months = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") summer...
# avg2.py # A simple program to average two exam scores # Illustrates use of multiple input print("This program computes the average of two exam scores") score1,score2=input("Enter two scores seperated by a comma :") average= (score1+score2)/2 print("The average of the scores is :",average)
def printinfo(arg1,*vartuple): print "Output is:" print arg1 for var in vartuple: print var return printinfo(10) printinfo(70,60,50)
import time ticks=time.time() print "Number of ticks since 12:00am jan1,1970:",ticks localtime=time.localtime(time.time()) print "Local current time:",localtime localtime=time.asctime(time.localtime(time.time())) print "Local current time:",localtime import calendar cal=calendar.month(2018,7) print "Here is the cal...
""" Introduction to storing functions in variables """ import unittest def surprise(): return 'SURPRISE!' # TODO 1) Change what is assigned into the func_1 variable so test_1 will pass func_1 = None # TODO 2) Change the return statement below so that test_2 will pass def pizza_surprise(): return None # TOD...
a=int(input('Enter')) b=int(input('Enter')) print('Mul of two values:-',a*b)
def ctof(celcius): if celcius < -273.15: return "Too low temperature" else: return celcius*9/5 + 32 temperatures=[10,-20,-289,100] file = open("ctof.txt", "w") for temp in temperatures: if type((ctof(temp))) == float: file.write(str(ctof(temp)) + "\n") file.close()
# Wykorzystując kod przygotowany do tego zadania, zamień klasy na namedtuple. # class Ojciec: # def __init__(self, imie, nazwisko, data_ur): # self.imie = imie # self.nazwisko = nazwisko # self.data_ur = data_ur from collections import namedtuple Ojciec = namedtuple('Ojciec', ['imie', 'na...
# Napisz prosty konwerter walut, który na wejściu przyjmie stringa składającego się z: # kwoty, waluty wejściowej, słówka kluczowego "to" i kwoty wyjściowej. # Użyj następujących kursów: 1 PLN to 1000 USD, 1 PLN to 4505 EURO, 1 PLN to 100 JPY # Załóż, że konwersje są wykonywane tylko z lub do PLNów. # Dla zaawansowanyc...
"""Not Missing Docstring""" import math import random import this def nic_nie_robie(): """ funkcja kompletnie do niczego nie potrzebna :return: """ our_pi = math.pi random.randint(0, int(our_pi)) return this def podzielna(liczba, podzielna_przez): """ :param liczba: :param p...
def palindrome(string): # Defined Function to check if string is palindrome or not # Here the string and its reversed string is compared if equal then return True otherwise False # Here Slicing concept is used, The entire string is reversed by putting [ : : -1] if string == string[::-1]: ...
#Implement the class SubrectangleQueries which receives a rows x cols #rectangle as a matrix of integers in the constructor and supports two methods: #1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) #Updates all values with newValue in the subrectangle whose upper left #coordinate is (...
#!/home/francisco/Projects/Pycharm/py-binary-trees-draw/venv/bin/python # -*- coding: utf-8 -*- from node import Node class AVLTree: def __init__(self): self.root = None self.leaf = Node(None) self.leaf.height = -1 self.nodes_dict_aux = {} self.nodes_dict = {} def ins...
# Implement a class to hold room information. This should have name and # description attributes. class Room: def __init__(self, name, description): self.name = name self.description = description self.n_to = None self.s_to = None self.e_to = None self.w_to = None ...
name="tarena" pwd="123456" i=3 while i>0: n = input("请输入用户名") p = input("请输入密码") if name==n and pwd==p: break i-=1 print("输入错误,请重新输入") if i==0: print("3次机会已经用完") print("欢迎您回来")
str1=input("请输入几个字,判断是不是回文:") a=str1[::1] b=str1[::-1] if a==b: print(str1,"是回文") else: print("不是回文")
import random random_number = random.randint(0, 100) print('Welcome to the Guessing Game Challenge! \n\n' 'The program will randomly pick an integer number between 1 and 100. \n' 'The user must then guess what this number is in the least amount of \n' 'guesses as possible. After each guess, the prog...
import nltk, pickle import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import string ''' A class to allow for a Majority Votes Classifier System The result with the most votes is returned as the classifier's answer ''' class MajorityVotesClassifier(nltk.classify.api.Classif...
from datetime import date class Year: def __init__(self, name, start_calendar_year): self.name = name self.start_date = date(month=6, day=1, year=start_calendar_year) self.end_date = date(month=5, day=31, year=start_calendar_year + 1) def __repr__(self): return '<Year {}>'.for...
#!/usr/bin/python3 # Implement PKCS#7 padding # A block cipher transforms a fixed-sized block (usually 8 or 16 bytes) of plaintext into ciphertext. # But we almost never want to transform a single block; we encrypt irregularly-sized messages. # # One way we account for irregularly-sized messages is by padding, creati...
# I found this approach simpler and easier to understand for people dreading the DP approach. So take a look. # Approach: From centre expand outward till you find longest substring for each of the characters in the string. # Traverse the whole string once and for each character, consider it as the centre of palindrome...
#!/usr/bin/env python #-*- coding: utf-8 -*- __author__ = 'znlccy znlccy0603@163.com' class ShowDict(object): '''该类用于展示字典的使用方法''' def __init__(self): self.spiderMan = self.createDict() #创建字典 self.insertDict(self.spiderMan) #插入元素 self.modifyDict(self.spiderMan) ...
import time from Queue import PriorityQueue import itertools class Solver: def __init__(self, problem, algorithm): self.num_visited = 0 self.algorithm = algorithm self.problem = problem self.max_mem = -1 def solve(self): result = None start = time.time() ...
def generate_concept_HTML(concept_title, concept_notes): html_part_1 = ''' <div class="concept"> <div class="concept-title"> ''' + concept_title html_part_2 = ''' </div> <div class="concept-notes"> ''' + concept_notes html_part_3 = ''' </div> </div>''' full_html = ht...
# testing purposes to find real cost from collections import deque def bfs(puzzle): queue = deque() seen = set() queue.append(puzzle.get_state()) queue.append(None) seen.add(puzzle.get_state()) cost = 0 while True: top = queue.popleft() if top is None: ...
""" Using the iterative parsing to process the map file and find out not only what tags are there, but also how many, to get the feeling on how much of which data you can expect to have in the map. Fill out the count_tags function. It should return a dictionary with the tag name as the key and number of times this tag...
import datetime class Horaire(): """ Save only hours and minutes. Provide some counts. Take silently count of passed day """ def __init__(self, h=0, m=0): self.h, self.m = h, m self.days = 0 # incremented when a day pass self._normalize() def __add__(self, othr...
# Ces programmes sont sous licence CeCILL-B V1. # Voici un programme qui résout l'équation du second degré # a x^2 + b x + c = 0 from math import sqrt a = float(input()) b = float(input()) c = float(input()) # Test du coefficient dominant if a == 0.0: print("Pas une équation du second degré") else: # Calcul du dis...
""" Operadores Lógicos and, or, not in e not in """ # # In[2]: a = 2 # In[3]: b = 2 # In[4]: c = 3 # # In[5]: a == b and b < c # Out[5]: True # Int[6]: a == b or b < c # Out[6]: True # # Int[7]: not a == b and not b < c # (Verdadeiro e False) = False # comparacao1 and comparacao # Verdadeiro ou Verdadeiro # comp1 OR...
""" Operadores Relacionais - Aula 12 == igualdade > maior que >= maior que ou igual a < menor que <= menor que ou igual a != dirente """ # Os operadores relacionais são feitos justamente para realizar comparações entre coisa certo # Desses aqui qualquer um desses operadores sempre que eles forem executados a expressa...
""" Funções (def) em Python - *args **kwargs Word argumentos Os argumentos posso utilizar dentro das funções Eu chamo a função e coloco o nome da função e passo os argumentos citando o valor do 2 a 1. Uma coisa que eu não posso fazer aqui por exemplo se eu tivesse mais um argumento aqui por exemplo A6, só que se ...
""" Basicamente pra treinar unir as coisas que a gente aprendeu ate nesse momento A gente vai utilizar os laços formam a estrutura de repetiçao """ print('Texto explicativo.') print() perguntas = { 'Pergunta 1': { 'pergunta': 'Quanto e 2+2? ', 'resposta': {'a': '1', 'b': '4', 'c': '5',}, ...
Precedência dos Operadores Aritméticos Assim como aprendemos na matemática, operadores têm uma certa precedência que pode ser alterada usando os parênteses (como descrito na aula anterior). Abaixo, segue uma lista mais precisa de quais operadores tem maior prioridade na hora de realizar contas mais complexas (de maior...
# def funcao(args, arg2): # return arg * arg2 # # var = funcao(2, 2) # print(var) lista = [ ['P1', 13], ['P2', 6], ['P3', 7], ['P4', 50], ['P5', 8], ] print(sorted(lista, key=lambda i: i[0], reverse=True)) print(lista) """ esses dois numeros multiplicados na tela """
""" add (adiciona), update (atualiza), clear, discard union | (une) intersection & (todos os elementos presentes nos dois sets) difference - (elementos apenas no set da esquerda) symmetric_difference (elementos que estao nos dois sets) """ l1 = ['Luiz', 'Joao', 'Maria'] l2 = ['Joao', 'Maria', 'Maria', 'Luiz', ...
""" Planetary Gravity Calculator Given the dimensions of several planets and an object's mass, calculate the amount of force exerted on an object's surface using Newton's Law of Universal Gravitation: F = G * ((M1 * M2) / D) Example: Input: Object mass = 100 kg Number of planets = 4 List of planets (nam...
""" Given a number of card decks, determine the probability that a blackjack hand will be dealt by the dealer. """ import random def getIntRange(low, high, prompt="", errmsg=""): if prompt == "": prompt = "Please enter the number of decks (%d-%d): " % (low, high) if errmsg == "": errmsg = "Ple...
""" Given a number of potential jobs/workers, assign jobs to workers based on unique skill matches. My solution didn't work, but I've included the most elegant solution presented on Reddit. """ def my_solution(): num_jobs_workers = int(raw_input("How many jobs/workers? ")) job_input_count = num_jobs_workers ...
print("|--- 欢迎进入通讯录程序 ---|") print("|--- 1:查询联系人资料 ---|") print("|--- 2:插入新的联系人 ---|") print("|--- 3:删除已有联系人 ---|") print("|--- 4:退出通讯录程序 ---|") contacts = {'闫':'1','帅':'2','舟':'3'} while 1: instr = int(input('\n请输入相关得代码指令:')) if instr == 1: name = input('请输入联系人姓名:') if name in contacts: ...
import copy import buscas import expansaoJogo import time print("-----------------------------") print("--------JOGO DOS 8 ----------") print("-----------------------------") #time.sleep(1) continuar = 1 print("Esse jogo pode ser resolvido através de buscas de Inteligência Artificial") while(continuar == 1)...
import numpy as np import csv import pandas as pd import os import pandas as pd import queue import threading import datetime import time csv.field_size_limit(1000000000) def count_csv_rows(csv_file_name): """This function is to get the row number of a csv file.""" with open(csv_file_name) as csvfile: ...
# -*- coding: utf-8 -*- """ Created on Tue Jun 12 15:25:22 2018 @author: Anuj Rohilla """ #importing the required modules import cv2 import numpy as np #creating a blank screen rect = np.zeros((300,300), dtype = "uint8") #creating rectangle in the previously created blank screen cv2.rectangle(rect, (25,25),(275,275)...
from types import List class Solution: def search(self, nums: List[int], target: int) -> int: low = 0 high = len(nums) - 1 while low <= high: middle = (low + high) // 2 if target == nums[middle]: return middle elif target < nums[middle]: ...
""" Contém as implementações de arquiteturas de CNN. [LeNet5] - CNN inspirada na arquitetura de LeCun [1], com algumas alterações nas funções de ativação, padding e pooling. [1] http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf """ # importar os pacotes necessários from keras.models import Sequential from keras.la...
# Taller 2 # Procesamiento de imagenes y visión # Manuela Bravo Soto # IMPORTACIONES import numpy as np # Del módulo numpy import cv2 # Del módulo opencv-python import math # Del módulo math #CLASE imageShape class imageShape: # CONSTRUCTOR # Recibe como parámetros el ancho y el alto de la image...
import sys import math def quicksort_count_first(seq): def sort(seq, begin, end): if begin >= end: return 0 p, m = begin, begin for i in range(begin+1, end): if seq[i] < seq[p]: seq[i], seq[m+1] = seq[m+1], seq[i] m += 1 seq...
def merge_sort(seq): if len(seq) < 2: return seq middle = len(seq) / 2 left = merge_sort(seq[:middle]) right = merge_sort(seq[middle:]) i, l, r = 0, 0, 0 while l < len(left) and r < len(right): if left[l] < right[r]: seq[i] = left[l] l += 1 else:...
import matplotlib.pyplot as plt # The slices will be ordered and plotted counter-clockwise. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = (0, 0, 0, 0) # explode a slice if required plt.pie(sizes, explode=explode, labels=labe...
''' Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой ''' def user_description(name, surname, birthday='...
from random import randint # BankAccount class creation class BankAccount: # BankAccount instance variables def __init__(self, full_name, account_number, routing_number, balance): self.full_name = full_name self.account_number = account_number self.routing_number = routing_number ...
# crop_by_percent_value.py import os from PIL import Image import argparse # TODO: 4.2 centre square/rectangle crop by user-determined percentage (crop to 50%/70%) crp_p def crop_by_percent(w_percent, h_percent, source, destination=''): """ crop the image by given pixels precentage usage: crop_by_percent_...
# I want to see if i can make a multi input chatbot with the small knowledge that i have. def chat_bot1(): print("Hello and welcome") response_1 = input("How are you?") if response_1 == "Fine": print("That is great") print("What are you doing today?") response_2 = input("Are you wor...
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ cd = {} # Dictionary to track history of number seen in same column grid = {} # Dictionary to track history of number seen in same grid ...
# Recursive implementation class Solution(object): def combo(self, n, ans, s=0, c=0, p=""): if c==n: # All starting parantheses have been closed with equal numbers of valid closing parantheses for current permutation ans.append(p) # Append latest calulated permutation to final answer...
l = list() n = int(input()) def function(l, n): l = [i for i in range(n) if i % 3 == 0 or i % 5 == 0] return sum(l) print(function(l, n))
""" 647. Palindromic Substrings Medium Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Input: "abc" Output: 3 Explanation: Three palin...
""" 740. Delete and Earn Medium Given an array nums of integers, you can perform operations on the array. In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1. You start with 0 points. Return the maximum number of point...
import re def check(filename, empty_sep_mode): """ Ensures the numbering and title are separated from each other with a dash and not with a dot or not separated at all. This assumes numbering is already done, as numbering handler is called before this. Setting empty_sep_mode to True makes separators b...
import numpy as np def letter_to_vector(character): if ord(character) < 97 or ord(character) > 122: raise Exception('Must be ascii lowercase letter') vector_matrix = np.eye(26) index = ord(character) - 97 vector = vector_matrix[index] return np.array(vector) def vector_to_letter(vector):...
#!/usr/bin/python from math import sqrt,fmod def multipliers(number): s = int(sqrt(number)) r = [] for a in xrange(2,s+1): while fmod(number,a) == 0: r.append(a) number = number / a return r def equation(a, b, c): r = [] d = b**2-4*a*c if d>0: r.append((-b+sqrt(d))/(2*a)) r.append((-b-sqrt(d))/(2*...
#1. Create a greeting for your program. print("Welcome to the band name generator.") #2. Ask the user for the city that they grew up in. city = input("Which city did your grow up in?") print(city) #3. Ask the user for the name of a pet. pet = input("What is the name of a pet?") #4. Combine the name of their city...
# coding=utf-8 import sys import time import warnings import drawing as dr # Constants # Константы accuracy = 0.1 ** 20 # Coefficients of a polynomial # Коэффициенты полинома coefficients = [1, 3, -24, 10, 13] # The polynomial at the point # Полином в точке def f(point, a=coefficients): result = 0 power = ...
def urlify(char_list, str_length): num_of_spaces = 0 for i in range(str_length): if char_list[i] == ' ': num_of_spaces += 1 total_length = str_length + num_of_spaces * 2 for i in range(str_length-1, -1, -1): total_length -= 1 if char_list[i] == ' ': char_...
import numpy as np from random import shuffle import scipy.sparse def softmax_loss_naive(theta, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs: - theta: d x K parameter matrix. Each column is a coefficient vector for class k - X: m x d array of data. Data are d-dimensional ro...
#STRING FORMATTING:: a = int(input("ENTER FIRST VALUE::")) b = int(input("ENTER SECOND VALUE::")) c = int(input("ENTER THIRD VALUE::")) avg = (a+b+c)/3 print(f"AVERAGE OF THREE VALUES YOU ENTERED IS::{avg}")#this is string formatting #STRING INDEXING:: language="python" #INDEX VALUE OF EACH CHARACTER IS AS FOLLOWS::...
#WE CAN ASSIGN VALUES TO MORE THAN ONE VARIABLES SIMULTANEOUSLY IN A SINGLE LINE a,b = 6,4 print(a,b) c,d,e,f = "d","v","c","p" print(c,d,e,f) name,age = "DHRUV","20" print("HELLO "+name+" YOUR AGE IS "+age) x=y=z=1 #DECLARING MORE THAN ONE VALUES IN A SINGLE LINE print(x+y+z)
# Udacity Data Analyst Nanodegree # Technical Interview # Lesson 3. Searching and Sorting # Quiz: Binary Search Practice """You're going to write a binary search function. You should use an iterative approach - meaning using loops. Your function should take two inputs: a Python list to search through, and the value ...
#!/bin/python3 """ This is a subject for the security testing lecture. The program accepts arithmetic expressions and prints the result of calculating the expression. """ import pyparsing as pp import operator, sys def BNF(decorate): """This function returns the parser for the language of arithmetic expressions. "...
## IMPORTS from room import Room from player import Player from item import Money from item import Food # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dus...
class Node: def __init__(self): self.children = [] self.depth = 0 self.value = 0 class ORNode(Node): def __init__(self, s=None): Node.__init__(self) self.s = s def __str__(self): descendant = "" for c in self.children: c...
organisms = int(input("Enter the initial number of organisms: ")) rateOfGrowth = int(input("Enter the rate of growth: ")) numOfHours = int(input("Enter the number of hours to achieve the rate of growth: ")) totalHours = int(input("Enter the total hours of growth: ")) while numOfHours <= totalHours: organism...
class Film: def __init__(self,name,award,year): self.name = name self.award = award self.year = year def __str___(self): return f'name={self.name}\taward={self.award}\tyear={self.year}' class BaseScraper: # Should return a dict where keys are full names of festivals and val...
import csv def createStudentsList(): with open('Students.csv', 'rb') as csvfile: studentreader = csv.reader(csvfile, delimiter=',') for row in studentreader: addStudent(row) csvfile.close() class student(object): def f(self): data = { 'fname' : 'firstname', ...
#TowerofHanoiEasy.py def towh(k): if k==1: return 1 else: return(2*towh(k-1)+1) def tow_o_h(k,a,c,temp): if k==0: return else: tow_o_h(k-1,a,temp,c) print "Move ",k,"from",a,"to",c," " tow_o_h(k-1,temp,c,a) if __name__ == '__main__': t = int(raw_input()) for i in range(0,t): b = int(raw_input()) ...
class Node: def __init__(self,data): self.data = data self.next = None class Linkedlist: def __init__(self,node): self.head = node if __name__ == '__main__': n = Node(100) h = Linkedlist(n) second = Node(200) n.next = second third = Node(500) second.next = third while(h.head!=None): print h.hea...
#quick_sort.py #Non Permutative way def quick_sort(A): quick_sort2(A,0,len(A)-1) def quick_sort2(A,low,hi): if low < hi: p = partition(A,low,hi) quick_sort2(A,low,p-1) quick_sort2(A,p+1,hi) def partition(A,low,hi): pivotIndex = get_pivot(A,low,hi) pivotValue = A[pivotIndex] A[pivotIndex],A[low] = A[low...
#Arraybasedqueue.py class ArrayQueue: DefaultSize = 10 def __init__(self): self._data = [None]*ArrayQueue.DefaultSize self._size = 0 self._front = 0 def __len__(self): return self._size def is_empty(self): return self._size==0 def first(self): if self.is_empty(): raise Empty('Queue is Empty...
#Reverse_string.py #Still has to be refined def revstr(S,low,high): if low<high: return [S[high],revstr(S,low+1,high-1),S[low]] if __name__ == '__main__': Str = "Revannth" St = " ".join(map(str,revstr(Str,0,len(Str)-1))) print St
#!/usr/bin/python import re import sys def printUsage(): print "Usage: inputFile outputFile options" print "options is either append [-append=number] or replace [-replace=index,number]" print "for example:" print " input.txt output.txt -append=0.25" print "will read input.txt and append 0.25 to every line and...
""" 希尔排序: 希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序,是直接插入排序算法的一种更高效的改进版本。 希尔排序是非稳定排序算法。该方法因DL.Shell于1959年提出而得名。 希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序; 随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。 思路: 希尔排序是插入排序的改进,所以还是安装插入排序写 但是进行比较时,引入了gab值 最优时间复杂度:根据步长序列的不同而不同 最坏时间复杂度:O(n2) 稳定...
class Entrada: def __init__(self): self.estados = 0 self.simbolosentrada = 0 self.simbolosfita = 0 self.numTransicoes = 0 self.listEstados = list() self.alfabetoentrada = list() self.alfabetofita = list() self.transicoes = list() self.fita = "" linha = input().split(' ') self.estados = int(linh...
#list fruit = list() print(fruit) fruit = [] print(fruit) fruit = ["Apple", "Orange", "Pear"] print(fruit) #toridasi fruit.append("Baanana") fruit.append("Peach") print("fruit = ", fruit) print("fruit_0 = ", fruit[0]) print(fruit[1]) print(fruit[2]) #append random =[] random.append(True) random.append(100) rando...
user_seconds = int(input('Введите количество секунд: ')) hour = user_seconds // 3600 seconds = user_seconds % 60 minute = int(user_seconds - (hour * 3600) - seconds) // 60 print(f'Время {hour}:{minute}:{seconds}')
#WAP to take input of sequence of comma-seprated numbers and generate a list and a tuple like :- # ['1','2','3'] #('1','2','3') values=input() list=values.split(",") #looked for a way to split "," on the internet found this split function tuple=tuple(list) #used the hint from the mail print (list) print (tuple)...