text
stringlengths
37
1.41M
salario = float(input('Digite o salário do funcionário: R$')) if salario > 1250: print('O salário atualizado com o aumento é de R${:.2f}'.format(salario * 10 / 100 + salario)) else: print('O salário atualizado com o aumento é de R${:.2f}'.format(salario + salario * 15 / 100))
from random import shuffle n1 = input('Digite o nome do primeiro aluno: ') n2 = input('Digite o nome do segundo aluno: ') n3 = input('Digite o nome do terceiro aluno: ') n4 = input('Digite o nome do quarto aluno: ') lista = [n1, n2, n3, n4] shuffle(lista) print ('A ordem de apresentação é: {}'.format(lista))
nomecompleto = str(input('Digite seu nome completo: ')).strip() print('Analisando seu nome...\n') print('Seu nome em maiúsculo é:',nomecompleto.upper()) print('Seu nome em minúsculo é: ',nomecompleto.lower()) print('O seu nome completo tem {} letras'.format(len(nomecompleto) - nomecompleto.count(' '))) print('O seu pr...
'''def somar(a=0, b=0, c=0): """[Mostra a soma dos parâmetros passados] Arguments: a {[int or float]} -- [Primeiro parametro passados] b {[int or float]} -- [Segundo parametro passados] Keyword Arguments: c {int or float} -- [Terceiro parametro opcional] (default: {0}) ...
#lanche = 'Hambúrguer', 'Suco', 'Pizza', 'Pudim', 'Batata Frita' #Tuplas são imutáveis! #for c in range(0, len(lanche)): # print(f'Eu vou comer {lanche[c]} na posição {c}') #for comida in lanche: # print(f'Eu vou comer {comida}') #for pos, comida in enumerate(lanche): # print(f'Eu vou comer {comida} e na po...
""" Author: Nguyen Tan Loc Date: 25/08/2021 Problem: Write an algorithm that describes the second part of the process of making change (counting out the coins and bills) Solution: example, if you buy a dozen eggs at the farmers’ market for $2.39 and you give the farmer a $10 bill, she should return $7.61 to you. ...
""" Author: Nguyen Tan Loc Date: 7/10/2021 Problem: What is a mutator method? Explain why mutator methods usually return the value None. Solution: Mutator methods are the methods that are used to modify the internal elements of the mutable objects. The Mutable object means which can be modified. For example co...
""" Author: Nguyen Tan Loc Date: 7/10/2021 Problem: A file concordance tracks the unique words in a file and their frequencies. Write a program that displays a concordance for a file. The program should output the unique words and their frequencies in alphabetical order. Variations are to track sequences of two ...
""" Author: Nguyen Tan Loc Date: 16/10/2021 Problem: Darkening an image requires adjusting its pixels toward black as a limit, whereas lightening an image requires adjusting them toward white as a limit. Because black is RGB (0, 0, 0) and white is RGB (255, 255, 255), adjusting the three RGB values of each pixel...
""" Author: Nguyen Tan Loc Date: 22/10/2021 Problem: Write the code for a mapping that generates a list of the absolute values of the numbers in a list named numbers Solution: Map Function • Map is one of the higher order functions in python used to apply a specific function on all the elements of...
""" Author: Nguyen Tan Loc Date: 16/10/2021 Problem: The edge-detection function described in this chapter returns a black-and-white image. Think of a similar way to transform color values so that the new image is still in its original colors but the outlines within it are merely sharpened. Then, define a functi...
""" Author: Nguyen Tan Loc Date: 10/09/2021 Problem: Assume that x refers to a number. Write a code segment that prints the number’s absolute value without using Python’s abs function. Solution: x=int(input("Enter x:")) if x < 0: x = –x print("x: ",x) .... """
""" Author: Nguyen Tan Loc Date: 10/09/2021 Problem: Write a loop that prints your name 100 times. Each output should begin on a new line. Solution: for count in range(100): print('LeVanThe!') .... """
""" Author: Nguyen Tan Loc Date: 15/10/2021 Problem: The Turtle class includes a method named circle. Import the Turtle class, run help(Turtle.circle), and study the documentation. Then use this method to draw a filled circle and a half moon. Solution: .... """
""" Author: Nguyen Tan Loc Date: 1/09/2021 Problem: Light travels at 3 *108 meters per second. A light-year is the distance a light beam travels in one year. Write a program that calculates and displays the value of a light-year. Solution: """ # Compute the result rate = 3 * 10 ** 8 seconds = 365 * 24 * 6...
""" Author: Nguyen Tan Loc Date: 1/09/2021 Problem: Write a string that contains your name and address on separate lines using embeded newline characters. Then write the same string literal without the newline characters. Solution: """ print("TAN LOC \nQuang Ngai ")
#!/bin/python3 import math import os import random import re import sys # Complete the countSort function below. def countSort(arr): highest = int(arr[0][0]) for i in arr: if highest < int(i[0]): highest = int(i[0]) li = [] for i in range(highest + 1): li.append([]) len...
#!/bin/python3 import math import os import random import re import sys # Complete the anagram function below. def makingAnagrams(s1, s2): splited = [s1, s2] alphaCount = [{},{}] asciia = ord('a') for i in range(26): alphaCount[0][chr(i + asciia)] = 0 alphaCount[1][chr(i + asciia)] = 0...
# Learner: Truong Vi Thien (14520874) # Generate Gaussian blobs and clustering using K-Mean. import matplotlib.pyplot as plt import matplotlib matplotlib.style.use("ggplot") from sklearn.cluster import KMeans from sklearn.datasets.samples_generator import make_blobs # Create data n_samples = 1000 n_features = 2 x,...
li = input() if '-0' in li: print('Sorry! Please enter valid integers') else: try: li = li.split(',') li = [int(number) for number in li] li.sort() li.reverse() prime = [] other = [] for number in li: s = 0 for j in range(1, number ...
""" https://leetcode-cn.com/problems/lru-cache/ """ class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self.dic = {} self.head = None self.tail = None def get(self, key): """ :type ...
""" https://leetcode-cn.com/problems/card-flipping-game/ """ class Solution(object): def flipgame(self, fronts, backs): """ :type fronts: List[int] :type backs: List[int] :rtype: int """ same = [] diff = [] for i in range(len(fronts)): if ...
""" https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/ """ class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if len(nums) == 0: return [-1,...
import pandas as pd friends=[ {'name':'Jone','age':20,'job':'student'}, {'name':'Jenny','age':30,'job':None}, {'name':'Nate','age':30,'job':'teacher'} ] df=pd.DataFrame(friends) df=df[['name','age','job']] print(df.head()) print(df[1:3]) print(df.loc[[0,2]]) print(df[df.age>25]) print(df.query('age>25'...
#!/usr/bin/python # coding:utf-8 """ This program reads in the CSV file, provide the option to manipulate per line of the file and save the modified data into a new CSV file. Usage: ManipulateCSVFile.py input.csv @author: Haiyang Cui """ import sys from pathlib import Path def main(argv): if l...
import random import os '''This file is to quickly build sample test data by outputing text files with randomized data and check computational speed''' #Time points for different sizes: # 50x50 # 100x100 # 300x300 # 500x500 # 800x800 # 1000x1000 def check_lines(my_file, max_user_number, new_file): f = open(...
# IfSpiral.py # Billy Ridgeway # Creates a square spiral. # Asks the user if they want to see a spiral. answer = input("Do you want to see a spiral? y/n:") if answer == 'y': # If the anser is yes, run the program. print("Working...") # Display a message the the program is working. impor...
from matplotlib.pyplot import plot, axis, show, legend mortgage_amount = float(input("How much is the mortgage for? ")) interest_rate = float(input("What is the interest rate (as a percentage)? "))/100 payment = float(input("How much are you paying per month? ")) max_months = 360 # Don't figure for more than 30...
''' У даному випадку рекурмія займає бцльше пам'яті Код доволі легко читати як в ітераційному так і в рекурсивному методах ''' from time import time def dig_root(number): if number < 10: # якщо число однозначне то це і буде корінь return number else: return dig_root( n...
import random class sources_num_1(): def sources_choice(self): a = ['广告','地推','老带新','上门'] return random.choice(a) def num_sources(self,list,num): for i in range(num): list.append(self.sources_choice())
''' Escriba una funcin que reciba un nmero entero del 1 al 7 y escriba en pantalla el correspondiente da de la semana. ''' def semanita(): numero=input("Introduce un numero del 1 al 7: ") if numero==1: print "Hoy es Lunes" if numero==2: print "Hoy es martes" if numero==3: ...
import math def findX(array, x): """ Given a sorted array, find the index of x if it exists, -1 otherwise. This can be done via binary search. """ left = 0 right = len(array) while (left < right): mid = int(math.floor((right + left)/2)) if (x == array[mid]): ...
''' Fibonacci functions with recursion and dynamic programming. ''' def fibonacci(i): ''' Calculates the ith fibonacci number. Runs in O(2^n) ''' if (i == 0): return 0 if (i == 1): return 1 return fibonacci(i-1) + fibonacci(i-2) fibs = [] def fibonacciDP(i): ''' Calculates the it...
def sort(A): mergeSort(A, 0, len(A)) def mergeSort(A, p, r): q = (p + r) // 2 if q > p: mergeSort(A, p, q) mergeSort(A, q, r) merge(A, p, q, r) def merge(A, p, q, r): L = [] R = [] for i in range(p, q): # p .. q-1 L.append(A[i]) L.append(float("inf")) fo...
class Solution: def reverseString(self, s) -> None: """ Do not return anything, modify s in-place instead. """ print(s.reverse()) l=Solution() l.reverseString(["h","e","l","l","o"])
li1= [9,8,4,1,2,2,0,5,5] # li2= list(set(li1)) # print(li2) # for i in list(set(li1)): # if i in li1: # li1.remove(i) nums= sorted(li1) print(nums) output=[] for i in range(1,len(nums)): if nums[i]==nums[i-1]: output.append(nums[i]) print(output) # print(li1)
#! /usr/bin/python import random """ Code for a presentation on dunder method basics """ class Color: _primary_colors = ['red', 'yellow', 'blue'] _secondary_colors = ['orange', 'green', 'purple'] _instance = None def __new__(cls, color): return super(Color, cls).__new__(cls) # Single...
# 新建元组类型 只可以访问,不可以增删改 # 用在方法入参,只读 atuple = (1,2,3,4) if __name__ == '__main__': print(atuple[0]) print(atuple[0:4]) # 不能被更改,所以报黄 atuple[0] = 5
# Purpose of Descriptors # without descriptors # class Person: # def __init__(self, name, age, bmi): # self.name = name # self.age = age # self.bmi = bmi # if isinstance(self.name, str): # print(self.name) # else: # raise ValueError("Name of the perso...
#Python-to-AQA-psudocode converter #By Andrew Mulholland aka gbaman # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
#Q1) Take an input year from user and decide whether it is a leap year or not. year=int(input("Enter The Year :- ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("%d is a leap year\n" %(year)) else: print("%d is not a leap year\n" %(year)) else: ...
import turtle n=int(input("想畫幾邊形")) hello=turtle.Turtle() for i in range(n): hello.forword(100) hello.left(360/n) while i<100: hello.forword(10+i)
# coding: utf-8 """Count words.""" def count_words(s, n): """Return the n most frequently occuring words in s.""" # TODO: Count the number of occurences of each word in s # TODO: Sort the occurences in descending order (alphabetically in case of ties) # TODO: Return the top n most freq...
class Node: def __init__(self, key): self.key = key self.left = None self.right = None def findPath( root, path, k): if root is None: return False path.append(root.key) if root.key == k : return True if ((root.left != None and findPath(root.left,...
#赋值初始化值 list2=[] list2=[1,2,3,4,5,"a",'b'] #print(list2[10],len(list2))#如果列表内数字大于列表的(长度-1),报错:IndexError: list index out of range print(list2[1],list2[-1])#输出是2,b;当列表后数字为负数表示从右往左数,为正数是则为从左往右数。 list2.append(100) print(list2) list2.append([9,30,45]) print(list2) list2.pop(0)#删除数组中第一个元素 print(list2) #多维...
class Person: def __init__(self, age, weight, height, first_name, last_name, catch_phrase): self.age = age self.weight = weight self.height = height self.first_name = first_name self.last_name = last_name self.catch_phrase = catch_phrase user = Person(25, 80, 177, "...
day= input().split() lis1={"Monday","Tuesday","Wednesday","Thursday","Friday"} lis2={"Saturday","Sunday"} i=0 n=len(day) for i in range(n): if day[i] in lis1: print("no") elif day[i] in lis2: print("yes")
# A pure function does not have side effects # functools is a toolbelt that can be used for functional tools that comes with python from functools import reduce # lambda expressions # a lambda experssion is a function that is only going to be used once # lambda param: action(param) my_list = [1,2,3] your_list = [10...
import matplotlib.pyplot as plt import numpy as np from matplotlib.animation import FuncAnimation plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(5, 3)) ax.set(xlim=(-3, 3), ylim=(-1, 1)) x = np.linspace(-3, 3, 91) t = np.linspace(1, 25, 30) X2, T2 = np.meshgrid(x, t) sinT2 = np.sin(2 * np.pi * T2 / T2.max(...
'''print("This is simulating the TNOR gate\n") print("Enter the following values : \n\n") A1=int(input("Enter A1 : ")) A2=int(input("Enter A2 : ")) B1=int(input("Enter B1 : ")) B2=int(input("Enter B2 : ")) C1=int(input("Enter C1 : ")) C2=int(input("Enter C2 : ")) L=1''' def blockpos(L, p1, p2): o=0 ...
class ListQ: def __init__(self): self.items = [] def isEmpty(self): if self.items == []: return True else: return False def put(self, item): self.items.insert(-1,item) def get(self): return self.items.pop(0) """class Sort(ListQ)...
# Problem 9 form Project Euler # The goal is to find a pythagorean triple with a sum of 1000 #Authored by Steve Saltekoff on Fri 21 2015 def pythtriptester(a,b,c,n): if a+b+c == n: return 1,a,b,c else: return 0,a,b,c def pythtrip(j,k,n): a = j**2 + k**2 b = 2*j*k c = j**2 - k**2 ...
#Project Euler, Problem 5 #The goal is to find the value of the smallest number that is evenly divisible by the positive integers 1 through 20. def primefactors(n): '''find the prime factors of a number, not including 1 and itself''' pdivs = [] i = 3 if n == 1 and i <= n**(1/2): pdivs = 1 ...
""" Problem ======= For every number i in range 1 to n, return the sum of the integer portions of the equation i * sqrt(2). S(n) = floor(sqrt(2)) + ... + floor(n * sqrt(2)) Example: S(3) = floor(sqrt(2)) + floor(2 * sqrt(2)) + floor(3 * sqrt(2)) = 1 + 2 + 4 ...
# se define la clase robot import random class Robot: x = 0 y = 0 max_x = 0 max_y = 0 min_x = 0 min_y = 0 def __init__ (self, max_x, max_y): self.x = random.randint (0, max_x - 1) self.y = random.randint (0, max_y - 1) self.max_x = max_x self.max_y = max_y ...
"""word count""" # recieve the text # split to words and save in a list # loop thro the list conting and saving the out def words(words): try: words = words.split() dic_out = {} for word in words: if word.isdigit(): if int(word) in dic_out: dic_out[int(word)] = dic_out[int(word)]+1 else: ...
#This is a simple Python program to print the weather at the user's location using their input city. #Also writes the data onto a file called weatherInfo.txt #Written by Suryanarayan Menon A (github.com/SuryaNMenon) for project submission for Shape-AI's free bootcamp. import requests import sys from datetime import d...
# -*- coding: utf-8 -*- """ Created on Sun Nov 19 14:36:18 2017 @author: James """ import numpy as np from ecdf_func import ecdf from pmf_func import pmf_plot import matplotlib.pyplot as plt samples = np.random.poisson(6, size=10000) x, y = ecdf(samples) pmf_plot(samples) _ = plt.plot(x, y, marker='.', linestyle=...
"""Customers at Hackbright.""" class Customer(object): """Ubermelon customer.""" # TODO: need to implement this def __init__(self, f_name, l_name, email, password): self.f_name = f_name self.l_name = l_name self.email = email self.password = password def __repr__(sel...
'''Objects to assign scores to ranks in ranked voting systems such as Borda. A rank scorer returns a list of numerical scores to be assigned to ranks given by voters. This is the essence of Borda count system, and rank scorers capture most of the variations there are in that system. ''' import abc from fractions impo...
import string def get_bigrams(in_text): """ Problem 7 This function takes string as input and returns bigram list """ text_list = in_text.split() bigram_list = [] for i in range(len(text_list)-1): bigram_list.append((text_list[i], text_list[i+1])) return bigram_...
def part_1(): total = 0 with open('input.txt') as lines: for line in lines: total += int(line) print(total) def part_2(): changes = [] with open('input.txt') as lines: for line in lines: changes.append(int(line)) frequencies = {0} curr_freq = 0 ...
#!/usr/bin/env python3 from collections import OrderedDict def count_islands(grid): rows, cols = len(grid), len(grid[0]) delta = [(-1, 0), (1, 0), (0, -1), (0, 1)] # (up, down, left, right) count = 0 for row in range(rows): for col in range(cols): if grid[row][col] == '1': ...
#!/usr/bin/env python3 def add_binary(a, b): if len(a) < len(b): a, b = b, a result, carry = [], 0 for i in range(len(a)): va = int(a[-(i+1)]) vb = int(b[-(i+1)]) if i < len(b) else 0 carry, v = divmod(va + vb + carry, 2) result.append(v) if carry: resul...
#!/usr/bin/env python3 def rotate(nums, k): ''' rotate the array to the right by k steps, k is non-negative ''' n = len(nums) k = k % n for i, j in [(0, n-k-1), (n-k, n-1), (0, n-1)]: while i < j: nums[i], nums[j] = nums[j], nums[i] i, j = i+1, j-1 if __name__...
#!/usr/bin/env python3 def find_distance(matrix, key): """Find the distance of the nearest key for each cell """ if not matrix or not matrix[0]: return matrix rows, cols = len(matrix), len(matrix[0]) delta = [(-1, 0), (1, 0), (0, -1), (0, 1)] def shortest(matrix, row, col, key): ...
#!/usr/bin/env python3 from collections import deque def unlock(target, deadends): delta = {str(i): [str((i+1) % 10), str((i-1) % 10)] for i in range(10)} def next_steps(current): for i, v in enumerate(current): for n in delta[v]: yield current[:i] + n + current[i+1:] ...
#!/usr/bin/env python import text_processor as tp if __name__ == '__main__': words = tp.get_paragraph_from_file(file_path='words.txt') words = tp.remove_special_char(text=words) words = tp.make_list_of_lower_word(paragraph=words) paragraph = tp.get_paragraph_from_file() paragraph = tp.remove_speci...
import pygame import surfaces #at this point what you have to do # is create a configuration for surface # create the surface(configuration can be reused) # create class SpritePlane(object): """ SpritePlane is a wrapper for Surface but it also contains sprites for collision detection , it is i...
import datetime now = datetime.datetime.today() print(now.day) print(now.weekday()) my_birthady = datetime.datetime(1974, 6, 19) print(my_birthady.weekday()) print(datetime.datetime.today() - my_birthady)
def pole_trapezu(a, b, h): """ :param a: podstawa 1 :param b: podstawa 2 :param h: wysokość :return: pole powierzchni """ a = 3 b = 9 h = 6.5 pole_tr = ((a + b) / 2) * h return ((a + b) / 2) * h print(f"pole trapezu o podstawach: {a}, {b} i wysokości: {h} wynosi: {pole_tr}") ...
# kwadraty = [x**2 for x in range (1, 101)] # print([i/10] for i in range(1,11)) # print = {(x, x**2, x**3) for x in range(1, 101)} zbior_napisow = {'abc', 'ala ma kota', 'slowacki wielkim poetą był', 'supermen'} print({x:len(x) for x in zbior_napisow}) print([x for x in range(1,101) if x%3==0])
data = [1, 2, 3, 4, 5, 6, 7] def przytnij(data, start, stop): resylt = [] for element in data: if start(element): if stop(element): break result.append(element) return result # print(lista, lambda x: x > 3) # print(lista, lambda x: x == 6)
# try: # plik = open("plik.txt") # print(plik) # except FileNotFoundError: # print("ni ma") # plik = open("plik.txt") # print(plik.read()) # plik.close() #ważne: zamykamy jak już skończymy korzystać with open("plik.txt") as plik: #to jest dobra praktyka. Wewnątrz tego bloku mamy otwarty plik.txt p...
import time licznik = 0 while licznik <= 10: print(licznik) time.sleep(1) licznik += 1 while licznik <= 100: print(licznik) time.sleep(0.5) licznik += 1 while licznik <= 500: print(licznik) time.sleep(0.25) licznik += 1 while licznik <= 1000: print(licznik) time.sleep(0.1) ...
#zbiór (set) - nieuporządkowana kolekcja elementów o szybkim czasie wstawienia/usunięcia/sprawdzenia czy element istnieje #zbiór przechowuje tylko unikalne element (bez powtórzeń), i w zupełnie losowej kolejności zbior = {1, 2, 3, 3, 3} print(type(zbior)) print(zbior) pusty = set() # nie można inaczej tworzyć pustego z...
print("napis") x= input ("podaj dane:") print("podałeś:", x) print(x*2) #Input zawsze jest domyślnie stringiem. Jeżeli to ma być liczba to trzeba to określić y = int(input("podaj dane:")) print("podałeś:",y) print(30*y) #zadanie miastoA = input("podaj miasto A:") miastoB = input("podaj miasto B:") DystansAB = int(inp...
# Zad. Napisz funkcję czy_podzielna(), która zwróci informację True/False czy n jest podzielne przez k #def czy_podzielna(n,k): # if n % k == 0: # return True # return False #print(czy_podzielna(4,3)) # Tak lepiej !!!!!!!!!!!!!! : def czy_podzielna(n,k): return n % k == 0 if czy_podzielna(10,2): ...
# standard ieee_754 - przechowywanie liczb zmiennoprzecinkowych # W systemach który muszą być precyzyjne nie używa się floatów tylko części dziesiętne też są int (tylko prezentowane jako dziesiętne) if 0.1 == 0.1: print("OK 1") if 1.0 == 1.0: print("OK 2") if 0.1 + 0.1 == 0.2: print("OK 3") if 1.0 + 1.0 ==...
# **5. Napisz klasę Zolw, która będzie przechowywała informację o położeniu żółwia na płaszczyźnie (2 liczby _rzeczywiste_) oraz kierunku wyrażonym w stopniach, w którym jest zwrócony. # Zolw powinien udostępniać metody: # - wypisz() - wypisuje położenie i zwrot żólwia, # - lewo(n) - obraca żółwia o n stopni w lew...
#0. Napisz funkcję, która sprawdzi czy podana lista jest posortowana rosnąco. def czy_rosnaca(lista): for i in range(len(lista)-1): if not lista[i] < lista[i+1]: return False return True print(f"{czy_rosnaca([1,3,5,4])=}")
x = None # kiedy nie chcemy nic przypisywać do zmiennej print(x) print(type(x)) if x is None: #operator porownania == sprawdza czy elementy są takie same. Is sprawdza czy elementy są TE same. print("x jest puste") if x is not None: print("x jest niepuste") #zadanie , niedokończone max = None min = None wh...
#### Zad: Napisz funkcję zaaplikuj(f, lista), która zwróci listę będącą wynikami funkcji f() wywołanej dla wszystkich elementów listy # [a, b, b] -> [f(a), f(b), f(c)] #zaaplikuj(dodaj10, [1,2,3,4]) == [11,12,13,14] def zaaplikuj(f, lista): wynik = [] for x in lista: wynik.append(f(x)) return wyn...
class Robot: def __init__(self,x,y,kierunek): self.x=x self.y=y self.kierunek = kierunek def wypisz(self): kierunki = ('N','E','S','W') print(self.x,self.y,kierunki[self.kierunek]) def lewo(self): self.kierunek = (self.kierunek -1) % 4 #modulo z liczb uj...
def fun(): print("asdf") x = fun #przypisujemy alias do funkcji x() #to samo co wywołanie fun() fun() def wykonaj(f,x): #przyjmuję funkcje f, argument x i wykonuje f(x) print("uwaga wywołuję f") f(x) #wypisz_arg(20) def wypisz_arg(x): print("Argument to", x) wykonaj(wypisz_arg, 20) wykonaj(print,...
""" Only three operations are premitted. push, pop, top """ import random from test import isSorted def sortedInsert(stack, element): if not stack or stack[-1] < element: stack.append(element) else: temp = stack.pop() sortedInsert(stack, element) stack.append(temp) def sortSt...
#!/usr/bin/python # -*- coding: utf-8 -*- """ https://www.geeksforgeeks.org/check-if-two-nodes-are-on-same-path-in-a-tree/ """ from collections import defaultdict class Graph: def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) self.inTime = {} se...
#!/usr/bin/python __author__ = "Vishal Jasrotia. Stony Brook University" __copyright__ = "" __license__ = "GPL" __version__ = "1.0" __maintainer__ = "Vishal Jasrotia" __email__ = "jasrotia.vishal@stonybrook.edu" __status__ = "" import sys class Node: def validate(f): def inner(*args, **kwargs): ...
""" Example : num = \"1234\" sumofdigit[0] = 1 = 1 sumofdigit[1] = 2 + 12 = 14 sumofdigit[2] = 3 + 23 + 123 = 149 sumofdigit[3] = 4 + 34 + 234 + 1234 = 1506 Result = 1670 Solution: For above example, sumofdigit[3] = 4 + 34 + 234 + 1234 = 4 + 30 + 4 + 230 + 4 + 1230 + 4 = 4*4 + 10*(3 + 23 ...
def activitySelection(activities): """ """ activities = sorted(activities , key = lambda x : x[1]) count = 1 i = 0 print(i) for j in xrange(1, len(activities)): if activities[j][0] > activities[i][1]: count += 1 i = j pri...
def jobSequencing(jobs): """ O(n^2) """ slots = [False]*(len(jobs)) result = [-1]*(len(jobs)) jobs = sorted(jobs , key = lambda x :x [2], reverse = True) for i in xrange(len(jobs)): for j in xrange(min(len(jobs), jobs[i][1]) - 1 , -1, -1...
from __future__ import print_function from linklist import SimpleNode as Node from linklist import printlist def reverseKNode(head, k ): count = 0 curr = head prev = None while count < k and curr is not None: next = curr.next curr.next = prev prev = curr curr = ne...
import random, time def binarysearchIter(nums,val, left, right): if left <= right: mid = left + (right - left)/2 if nums[mid] == val: return mid elif val < nums[mid]: return binarysearchIter(nums, val, left, mid - 1) else: return bin...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Algorithm 1) Create a set mstSet that keeps track of vertices already included in MST. 2) Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE. Assign key value as 0 for the first vertex so that it is picked first. 3) While mstSet doe...
""" Construct Tree from given Inorder and Preorder traversals Let us consider the below traversals: Inorder sequence: D B E A F C Preorder sequence: A B D E C F """ from __future__ import print_function from tree import Node from insertNode import insert def search(inorder, val, low, high): for i in xrange(low,...
printed = [] def fib(n): if n<2: if n not in printed: printed.append(n) print(n) return n else: num = fib(n-2) + fib(n-1) if n not in printed: print(num) printed.append(n) return num print(fib(10)) print(len(...
# -*- coding:utf-8 -*- """Kadane\’s Algorithm """ from sys import maxint def findMax(nums): maxsum = -maxint max_so_far = 0 start = 0 end = 0 s = 0 for i in xrange(len(nums)): max_so_far += nums[i] if maxsum < max_so_far : maxsum = max_so_far ...
from insertNode import insert def deleteLast(root, last_val): queue = [root] while queue: size = len(queue) for i in xrange(size): node = queue.pop(0) if node.left: if node.left.data == last_val: del node.left ...
def towerofhanoi(n, from_rod, to_rod, aux_rod): if n == 1: print("Move disk %s from %s to %s"%(n, from_rod, to_rod)) return towerofhanoi(n-1, from_rod, aux_rod, to_rod) print("Move disk %s from %s to %s"%(n, from_rod, to_rod)) towerofhanoi(n-1, aux_rod, to_rod, from_rod) def ...
from linklist import SimpleNode as Node from linklist import printlist def evenodd(head): head1 = Node(-1, None) head2 = Node(-1, None) h1 = head1 h2 = head2 while head is not None: h1.next = head h1 = h1.next head = head.next if head is not None: h...