text
stringlengths
37
1.41M
class LinkedNode(object): def __init__(self, data): self.data = data self.nextnode = None def print_list(head): temp_head = head while temp_head: print temp_head.data # print temp_head temp_head = temp_head.nextnode print def reverse_list(original_h...
def is_possible(a, b): return sum(a) == sum(b) def find_diff(a, b): total_equal = 0 for i in range(len(a)): if a[i] > b[i]: total_equal += a[i] - b[i] return total_equal n = int(raw_input().strip()) a = map(int, raw_input().strip().split()) b = map(int, raw_input().strip(...
def mysort(A, p, n): result = [] i = 0 j = p while i < p and j < n: if A[i] < A[j]: result.append(A[i]) i += 1 else: result.append(A[j]) j += 1 while i < p: result.append(A[i]) i += 1 while j < n: resu...
""" Input: [-2, -3, 4, -1, -2, 1, 5, -3] Output: 12 Two subarrays are [-2, -3] and [4, -1, -2, 1, 5] Input: [2, -1, -2, 1, -4, 2, 8] Output: 16 Two subarrays are [-1, -2, 1, -4] and [2, 8] """ Input= [-2, -3, 4, -1, -2, 1, 5, -3] total = sum(Input) left = 0 right = total mx = 0 print Input print total for i ...
''' 8) Escreva um programa que leia dois números. Imprima a divisão inteira do primeiro pelo segundo, assim como o resto da divisão. Utilize apenas os operadores de soma e subtração para calcular o resultado. Lembre-se de que podemos entender o quociente da divisão de dois números como a quantidade de vezes que ...
'''2) Faça um programa para escrever a contagem regressiva do lançamento de um foguete. O programa deve imprimir 10, 9, 8, ..., 1, 0 e Fogo! na tela.''' import time quantidade = 10 numeros = list(range(1,quantidade+1)) while len(numeros) > 0: print(numeros.pop()) time.sleep(1) print('0... Fogo!')
#Midterm Exam in Your Home_2_안예림 #각 돌은 순서대로 1~N까지 번호가 붙어 있으며,2차원 배열을 선언 n=int(input("돌의 개수 >> ")) d=[[0 for clo in range(2)] for row in range(n)] #각 돌에는 점수가 적혀있다. for i in range(n): d[i][0]=int(input("돌의 쓰여질 점수 >> ")) #돌을 밟을 때마다 돌에 쓰여진 점수를 누적해서 더해야 되고, #돌의 합이 최대가 되도록 징검다리를 건너고 싶다. score=0 def finish_n(i,d,scor...
# -*- coding: utf-8 -*- """ Created on Mon Aug 27 20:54:12 2018 @author: wyh """ """ Given a 32-bit signed integer, reverse digits of an integer. Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of t...
# -*- coding: utf-8 -*- """ Created on Thu Aug 30 10:37:39 2018 @author: wyh """ """ Given a linked list, remove the n-th node from the end of list and return its head. """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = ...
""" A module for containing any user facing text in the English language.""" from typing import Final APPLICATION_TITLE: Final[str] = "Phonetics Modeling Program" DIALOG_WINDOW_TITLE: Final[str] = "Request" MENU: Final[ str ] = """What do you want to accomplish? 1) view the English phoneme inventory (as IPA gra...
import sys import argparse from os import path import json from drawer import draw def main(): if len(sys.argv) < 2: raise Exception("Please provide json file") argparser = argparse.ArgumentParser(description='Parse and draw from json') argparser.add_argument('input', help='path to json') argparser.add...
TAKEN = 1 NOT_TAKEN = 0 class LinearEqn(object): def __init__(self,values,weights,capacity): """values and weights : list of ints capacity :an int """ self.values = values self.weights = weights self.capacity = capacity self.recursion = 0 self.solution = [] #don't know how 2 find d items which were p...
def add(param1, param2): result = param1 + param2 return result def multiply(param1, param2): result = param1 * param2 return result if __name__ == "__main__": # function call print(add(5, 10)) print(multiply(5, 10))
myName = input("your name: ") myAge = int(input("your age: ")) print("1. Hello World, my name is %s and I am %d years old." % (myName, myAge)) print("2. Hello World, my name is %s and I am %s years old." % (myName, myAge)) print("3. Hello World, my name is {} and I am {} years old.".format(myName, myAge)) print('4. He...
import numpy as np def skosnosc(x): n=len(x) srednia=np.mean(x) skos=[] for i in range(n): skos.append(float((x[i]-srednia)**3)) print('skosnosc wynosi ' + str(sum(skos)/n)) lista=[5.5,5.8,14.12,28.3,25.5,3.9,1.1] skosnosc(lista)
from hangman.game import Hangman """ Hangman Runner @Author Afaq Anwar @Version 02/21/2019 """ current_game = Hangman() print("Welcome to Hangman!" + "\n" + "Attempt to guess the word!") current_game.update_display() while not current_game.game_over: current_game.guess(input("Type...")) current_game.update_di...
# -*- coding: utf-8 -*- """ Created on Sun Oct 1 12:30:35 2017 @author: smvaz """ #improting requeired lib import math def POISSON(Lambda, y): #define a function to calculate poisson dist pmf= math.exp(-Lambda) * Lambda**y / math.factorial(y) return pmf # a for loop for calculation of 4=<y=<9 Lambda=3 ...
# JSON is commonly used with data API's. Here how we can parse JSON into a Python Dictionary import json # Sample JSON userJSON = '{"first_name": "Nandy", "last_name": "Mandy", "age": 23}' # Parse to dictionary user = json.loads(userJSON) print(user) # dictionary to JSON car = {'make': 'Aston', 'model': 'Martin', ...
print("Welcome to Good Burger") total=0 #iteration 1 sandwich=input("What kind of sandwich do you want, chicken for $5.25 (c), beef for $6.25 (b), or tofu for $5.75 (t)? ") print(sandwich) if sandwich=="c": total+=5.25 elif sandwich=="b": total+=6.25 elif sandwich=="t": total+=5.75 #iteration 2 beverage=i...
#!/usr/bin/python3 from string import ascii_lowercase lines = [] with open("input.txt") as filehandler: for line in filehandler: lines.append(line[:len(line) - 1]) # PART ONE count_two_of_any_letter = 0 count_three_of_any_letter = 0 for line in lines: found_exactly_two = False found_exactly_th...
""" K-Nearest Neighbours -> Is a classification algorithm wich classify cases based on their similarity to other cases; -> Cases that are near each other are said to be neighbors; -> Similar cases with same class labels are near each other. How it really works? 1. Pick a value for K; 2. Calculate the distance of unk...
#import pymongo import pymongo from pymongo import * #connect python to mongo client = MongoClient() #connect to a new or existing Data Base Data_Base = client.database #Data_Base is the name python will use to refer to the database #DB is the name of the database in mongo(or the oone that will e created) #Then conn...
from threading import Thread,Condition from time import sleep # notify(n=1)--> this method is used to immediately wake up one thread waiting on the condition.where n is number of thread need to wake up (by default value is 1) # notify_all()--> this metohd is used to wake up all threads waiting on the condition ...
################# #Tyler Robbins # #1/19/14 # #FTPConnect # ################# import sys, os from ftplib import FTP from getpass import getpass import platform if platform.system() == 'Windows': slash = "\\" else: slash = "//" while True: ulogin = True url = raw_input(">>> FTP server (example.com) or (ip.ip.ip:a...
usrinput=int(raw_input()) if usrinput<0: print "Negative" elif usrinput>0: print "Positive" elif usrinput==0: print "Zero"
def hcf1(x1,x2): while(x2!=0): t=x2 x2=x1%n2 x1=t return x1 def main(): m=int(input()) q=int(input()) (l,r)=([],[]) for i in range(m): l.append(int(input())) print(l) for c in range(q): x1=int(input()) x2=int(input()) r.append(hcf1(l[x1-1],l[x2-1])) for i in r: print(r) try: main() except: ...
def triplets(tot,l): n=len(l) for i in range(n-2): for j in range(i+1,n-1): for k in range(j+1,n): if l[i]+l[j]+l[k]==tot: return l[i],l[j],l[k] return 'none' def main(): n=int(input()) l=[] for i in range(n): l.append(int(input())) tot=int(input()) print(triplets(tot,l)) try: main() excep...
print('''you the scared night guard in an abandoned mansion in the middle of a forest, you see a ghost down the hall. What do you do?''') print('do you turn left and go into the closet, or do you turn right and jump out the window?') turn = input(' type left or right: ') if turn == 'left': print('you enter...
#!/usr/bin/env python import pprint pp = pprint.PrettyPrinter(indent=4) class Carta (): x=4 def __init__(self, palo=0, valor=0): self.palo = palo self.valor = valor def __str__(self): #return("aqui hay que devolver self.palo y self.valor") return("("+str(self.valor)+" "+self.palo+") ") class Mazo: #~ def...
''' Blockchain, Module 1 Created by: Isaac Harasty This python module is what is accomplished in the 'Module 1' Section of the slides that were submitted for this project. Creates a cryptographically linked chain of blocks with basic data fields, including Time Stamps, Block Index, the Previous Hash, and Nonce for mi...
import unittest from temptracker import TempTracker, InvalidTemperatureError, TempTrackerError class TestTempTracker(unittest.TestCase): """Test critical functionality for `TempTracker`. To keep things simple, specific sample test-values can be included below as class variables. """ _sample_nested_l...
""" Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [...
""" Two Sum II - Input array is sorted - https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numb...
""" Implementation of a dynamic array in python """ import unittest import random class Array: def __init__(self): self._capacity = 5 self._size = 0 self._array = [None for i in range(5)] def size(self): return self._size def capacity(self): return self._capa...
""" Prefix Sum Array """ """ Example of a prefix sum Array - geeksforgeeks.org Input : arr[] = {10, 20, 10, 5, 15} Output : prefixSum[] = {10, 30, 40, 45, 60} Explanation : While traversing the array, update the element by adding it with its previous element. prefixSum[0] = 10, prefixS...
""" Frievald's algorithm to chech matrix multiplication """ import random def mat_mul(A, B, n): """ A, B are two n*n square matrices Returns matrix C as the product of A and B """ C = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): ...
""" Valid Palindrome - https://leetcode.com/problems/valid-palindrome/ Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have...
""" Next Closest Time - https://leetcode.com/problems/next-closest-time/description/ Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused. You may assume the given input string is always va...
""" Convert BST to Greater Tree - https://leetcode.com/problems/convert-bst-to-greater-tree Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. Example: In...
""" https://www.hackerearth.com/codathon-nitbhopal/algorithm/new-government-new-name/ """ import string def type1(query, strg, str_dict): pos = int(query[1]) - 1 char = query[2] # Replacing in strg and updating values in dictionary str_dict[strg[pos]] -= 1 strg[pos] = char str_dict[char] ...
""" Repeated Substring Pattern Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. Example 1: Input: "ab...
""" Implementation of a Binary Tree """ class Node(object): """ A node contains some information """ def __init__(self, value): self.value = value self.parent = None self.left = None self.right = None def inorder(root): """ Prints the inorder traversal of a tree """ if root != None: inorder(root.left...
""" Evaluate Reverse Polish Notation - https://leetcode.com/problems/evaluate-reverse-polish-notation/ Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+",...
""" Island Perimeter - https://leetcode.com/problems/island-perimeter You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there...
""" Hamming Distance - https://leetcode.com/problems/hamming-distance The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: Input: x =...
""" Same Tree - https://leetcode.com/problems/same-tree Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. """ # Definition for a binary tree node. class TreeNode(...
""" Base 7 - https://leetcode.com/problems/base-7 Given an integer, return its base 7 string representation. Example 1: Input: 100 Output: "202" Example 2: Input: -7 Output: "-10" Note: The input will be in range of [-1e7, 1e7]. """ class Solution(object): def convertToB...
""" Max Consecutive Ones - https://leetcode.com/problems/max-consecutive-ones Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum ...
""" Average of Levels in Binary Tree - https://leetcode.com/problems/average-of-levels-in-binary-tree/ Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. Example 1: Input: 3 / \ 9 20 / \ 15 7 ...
""" Minimum Spanning Tree using Kruskal's and Prim's Algorithm """ from collections import defaultdict import heapq class Graph: def __init__(self, v): self.vertices = v self.graph = [] def add_edge(self, u, v, w): self.graph.append([u,v,w]) # find and union are used to quick...
""" Set Mismatch - https://leetcode.com/problems/set-mismatch The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number. ...
''''''''''''''''''''''''''''''''''''''''''''''''''' > System: Ubuntu > Author: ty-l8 > Mail: liuty196888@gmail.com > File Name: insertsort.py > Created Time: 2017-09-22 Fri 10:58 ''''''''''''''''''''''''''''''''''''''''''''''''''' # insert sort using binarySearch written by lty, which time complexity is ...
#!bin/python3 #Variables and methods quote = "All is fair in love and war." print(quote.upper()) #uppercase print(quote.lower()) #lowercase print(quote.title()) #title case print(len(quote)) name = "amani" #string age = 21 #int gpa = 3.7 #float print(int(age)) print(int(30.1)) print("My name is " + name + " and I ...
#! /usr/bin/python3 # -*- coding: utf-8 -*- """ Tools used to manipulate continued fractions Function names are converters from one number representation to another. bits: list of bits, the most significant one coming first. dec: float. cfrac: list of integers appearing in a continued fraction. The first eleme...
"""https://www.codeeval.com/open_challenges/21/""" import sys test_cases = open(sys.argv[1], 'r') def sum_digits(n): n = int(n) sum = 0 while (n/10 > 0): sum += n%10 n = n//10 print(sum) for test in test_cases: sum_digits(test) test_cases.close()
"""https://www.codeeval.com/open_challenges/20/""" import sys test_cases = open(sys.argv[1], 'r') def convert_lowercase(s): print(s.lower()) for test in test_cases: convert_lowercase(test) test_cases.close()
#!/usr/bin/python # Create a list of 5 IPs ip_list = ["10.1.2.4", "172.16.15.9", "154.69.45.26", "10.5.7.1", "10.7.96.5"] print(ip_list) # use append to add an ip to the end of the list ip_list.append("192.65.8.2") print(ip_list) # user extend to add two more ips to the end new_ips = ["192.168.1.1", "192.168.1.2"] ip_...
from game import * from collections import deque # Project main loop def game(levels): game = Game(levels) intro = run = True computer = human = choosingLevel = False while run: #MAIN MENU while intro: game.writeToScreen(center, "Press H to play in human mode. ", True) ...
time = [] while True: jogador = {} jogador = {'Nome':input('Nome: '), 'Partidas':int(input('Partidas jogadas: ')), } total_gols = 0 Gols = [] for p in range(0, jogador['Partidas']): gol = int(input(f'Gols marcados na partida {p+1}: ')) Gols.append(gol) t...
#Escopo de variáveis. Aula 21 Python Mundo 3 #Escopo local def teste(): x = 8 #Foi declarada dentro da função, logo a variável é local. Só vai funcionar nessa área. d = 1 #Cria uma variável nova. Local. Diferente do d global. print(f'Na função teste, a variável local x tem valor {x}') print(f'Na funçã...
#TRABALHANDO COM STRINGS #CONTA A QUANTIDADE DE LETRA A NUMA FRASE E INDICA SUAS POSIÇÕES while True: frase = input("Digite uma frase: ").strip().upper() if "SAIR" == frase: print("saiu", "\n") break elif "SAIR" != frase: print("ANALISANDO FRASE...") print("A letra A apar...
#DESAFIO DO PROCESSO SELETIVO DE 2020 - JAGUAR #Mabe S2 dados = [] #lista vazia dos dados while True: #dados = [] #lista vazia dos dados nome = input("Digite seu nome: ").strip().upper() #usuario digita um nome. strip() elimina os espaços. if nome == "SAIR": #Se o usuario digitar sair, para a execucao ...
#MaBe #Função que calcula a área de um terreno retangular def area(largura, comprimento): area = largura*comprimento print(f'A área do terreno é {area}m².') b = float(input('Largura [m]: ')) h = float(input('Comprimento [m]: ')) area = area(b, h)
#LÊ UM NOME COMPLETO E DIZ QUAL O PRIMEIRO NOME E QUAL O ÚLTIMO NOME while True: nome = input("Digite seu nome completo: ").upper().strip() n1 = nome.split() #fatia o nome. Divide em partes. Joga para uma lista. ult = len(n1) - 1 #len() conta as posições da lista. Me da a quantidade. ult = n1[ult] #f...
# Methacaracter plus + # Usado para uma ou mais correspondencias do padrao restante import re txt = 'maaano' x = re.findall('ma+n', txt) print (x)
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-compute-a-power-b '''Given 2 numbers - a and b, evaluate ab. Input Format First line of input contains T - number of test cases. Its followed by T lines, each line containing 2 numbers - a and b, separated by space. Constraints 30 points 1 <= T <...
def flipBits(n): res = "" for _ in range(32): res = res + str((n&1)^1) n = n>>1 return (int(res[::-1],2)) def flippingBits(n): return ((1<<32)-1)-n def flippingBits2(n): return ((1<<32)-1)^n if __name__ == '__main__': n = 4 print("{:032b}".format(n)) print(flipBits(n)...
''' https://www.interviewbit.com/problems/min-jumps-array/ Given an array of non-negative integers, A, of length N, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Return the minimum number of jumps required to reach the las...
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-rhymes '''Given is a wordlist L, and a word w. Your task is to find the length of the longest word in L having the longest common suffix with w. Input Format First line of input contains N - length of the list of words. The next N lines contains a ...
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-find-first-repeating-character '''Given a string of characters, find the first repeating character. Input Format First line of input contains T - number of test cases. Its followed by T lines, each line contains a single string of characters. Cons...
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-reverse-bits/submissions/code/1318356027 '''Given a number, reverse the bits in the binary representation (consider 32-bit unsigned data) of the number, and print the new number formed. Input Format First line of input contains T - number of test c...
''' https://www.interviewbit.com/problems/min-sum-path-in-matrix/ Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Example : Input : [ 1 3 ...
def perform_bubble_sort(blist): cmpcount, swapcount = 0, 0 for j in range(len(blist)): for i in range(1, len(blist)-j): cmpcount += 1 if blist[i-1] > blist[i]: swapcount += 1 blist[i-1], blist[i] = blist[i], blist[i-1] return cmpcount, swapcoun...
# Given a positive integer, print its binary representation. # # Input Format # # First line of input contains T - number of test cases. Its followed by T lines, each line containing a single integer. # # Constraints # # 1 <= T <= 10000 # 0 <= N <= 109 # # Output Format # # For each test case, print binary representati...
def prettyPrint(n): ans = [] for i in range(n): temp = [] k = n for j in range(i): temp.append(k) k -= 1 temp = temp + ([n - i] * (n - i)) temp = temp + temp[::-1][1:] ans.append(temp) for i in range(1,n): ans.append(ans[n-i-1])...
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-subsets-of-an-array/problem '''Given an array of unique integer elements, print all the subsets of the given array in lexicographical order. Input Format First line of input contains T - number of test cases. Its followed by 2T lines, the first lin...
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-check-anagrams '''Given 2 strings, check if they are anagrams. An anagram is a rearrangement of the letters of one word to form another word. In other words, some permutation of string A must be same as string B. Input Format First line of input co...
# https://www.hackerrank.com/contests/smart-interviews/challenges/si-distinct-elements-in-window '''Given an array of integers and a window size K, find the number of distinct elements in every window of size K of the given array. Input Format First line of input contains T - number of test cases. Its followed by 2T...
''' https://www.hackerrank.com/contests/smart-interviews-16b/challenges/si-range-sum-subarrays Given an array of integers and a range [A,B], you have to find the number of subarrays whose sum lies in the given range inclusive. Input Format First line of input contains T - number of test cases. Its followed by 2T line...
# Metodo count() ## Busca un elemento en una tupla y retorna el ## número de veces que se repita # t = (0, 1, 2, 3, 2, 4, 5, 2, 2) # print(t.count(2)) # print(t.count(5)) # a = ('manuel','oscar','manuel') # print(a.count('manuel')) # tupla = ('Curso', 15, True, 150.20, 150.20, False, 'Alumno') # print(tupla...
# # This file contains the Python code from Program 12.8 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm12_08.txt # class SetAsBitVect...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import itertools def start_at_three(): val = input("input some words or numbers: ").strip() while val != '': for el in itertools.islice(val.split(), 2, None): yield el val = input("input some words or numbers: ").strip() def itertools_tee(iterable, headsize...
# # This file contains the Python code from Program 6.13 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm06_13.txt # class QueueAsArray...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import time import pygame import math from pygame.locals import * pygame.init() screen = pygame.display.set_mode((600, 500)) pygame.display.set_caption("Draw Arcs") def draw_arc(): color = 255, 0, 255 width = 8 pos = 200, 150, 200, 100 start_angle = m...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- seconds_per_hour = 60 * 60 print("seconds_per_hour = ", seconds_per_hour); seconds_per_day = seconds_per_hour * 24; print("seconds_per_day = ", seconds_per_day); print("seconds_per_day / seconds_per_hour = ", seconds_per_day / seconds_per_hour); print("seconds_per_day...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def finally_test_trap_one(): print("hello, finally test ---> trap 1") while True: try: raise ValueError("this is value error") except NameError as e: print("NameErorr {}".format(e)) break finally: print("Finally here, should never 'break' here") ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #years_list = [ y for y in range(1987, 1987 + 6) ] years_list = [ y + 1987 for y in range(6) ] #years_list = list(range(1987, 1987 + 6)); print(years_list) print("birthday = ", years_list[0]) print("oldest = ", years_list[-1]) things = ["mozzarella", "cinderella", "...
#!/usr/bin/env python3 import random import time def quicksort(ary): print(ary) if len(ary) <= 1: return ary pivot = ary[len(ary)//2] _l = [x for x in ary if x < pivot ] _m = [x for x in ary if x == pivot ] _r = [x for x in ary if x > pivot ] return quicksort(_l) + _m + quicks...
# # This file contains the Python code from Program 7.9 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm07_09.txt # class OrderedListAs...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def do_test_try_catch(): a = 1 try: print("hello, a") a = 2 return a except: print("catched...") return a -1 else: print("else...") a = 3 finally: print("finally...") a = 10 ...
# # This file contains the Python code from Program 8.2 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm08_02.txt # class Float(float, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys, math, random from datetime import datetime, date, time import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((600,500)) font1 = pygame.font.Font(None, 30) pos_x = 300 pos_y = 250 white = 255,255,255 blue = 0,0,255 black...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from ep import timeit from ep import show_item_info import sys def _index_words(text): result = [] if text: result.append(0) for index, l in enumerate(text): if l == ' ': result.append(index + 1) return result @show_item_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class OnlyOne: class __OnlyOne: def __init__(self): self.val = None def __str__(self): return repr(self) + self.val instance = None def __new__(cls): if not OnlyOne.instance: OnlyOne.instance = ...
# 2^(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # What is the sum of the digits of the number 2^(1000)? # LOGIC # left shift of 1 is powering by 2, then add the digits (count, n) = (0, 1 << 1000) while (n >= 1): count += n % 10 n /= 10 print count
# You are given the following information, but you may prefer to do some research for yourself. # * 1 Jan 1900 was a Monday. # * Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-eight, rain or shine. # ...
# Take the number 192 and multiply it by each of 1, 2, and 3: # 192 x 1 = 192 # 192 x 2 = 384 # 192 x 3 = 576 # By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) # The same can be achieved by starting with 9 and multi...
def delete_letters(letter, text): up_letter = str.upper(letter) low_letter = str.lower(letter) change_text = "" str(change_text) str(text) for i in text: if i != low_letter and i != up_letter: change_text += i return change_text print(delete_letters("a", "Bartosz"))
#!/usr/bin/python3 import sys if __name__ == '__main__': """Prints the argument list passed to the program The program takes all the arguments starting from the second and prints the number of arguments and their value """ av = sys.argv l_av = len(av) - 1 if l_av > 1: print(l_av,...
#!/usr/bin/python3 """ A integer validator module """ class BaseGeometry: """ A super class to implements geometrical shapes """ def area(self): """ Raises an exception when you call this function """ raise Exception('area() is not implemented') def integer_valid...