text
stringlengths
37
1.41M
NUMBER = int(input()) horas = int(input()) valor_hora = float(input()) valor_hora = float('{0:2}'.format(valor_hora)) SALARY = float(horas * valor_hora) print('NUMBER = {}\nSALARY = U$ {:.2f}'.format(NUMBER, SALARY))
# 791 Custom Sort String class Solution: def customSortString(self, order: str, str: str) -> str: c_str = Counter(str) custom_sorted = '' for char in order: if char in c_str: custom_sorted += char * c_str.pop(char) for char in c_str: ...
class HelloWorld: message = "" def set_message(self, str): self.message = str def get_message(self): return self.message def print_message(self): print(self.message) obj = HelloWorld() obj.set_message("Hello World!") obj.print_message()
# -*- coding: utf-8 -*- """Test unitarios para el módulo ataque.""" import unittest from ataque import Ataque, Ataque_especial from elemento import Elemento class TestAtaque(unittest.TestCase): def setUp(self): pass def test_se_puede_crear_un_ataque_de_cada_elemento(self): a = Ataque(Element...
""" Question: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. And what are the time complexity and space complexity of your answer? Our approach: 1. For each row i, for each column j, we compute (and update) heights[j], the number of consecutive 1's...
#!/usr/bin/python import argparse def find_max_profit(prices): result = [] index = 0 for x in prices: for y in range(index, len(prices)): if x == prices[y]: continue else: result.append(prices[y]-x) index += 1 maxProfits = max(r...
import turtle import time def drawgap(): turtle.penup() turtle.fd(5) turtle.pendown() def drawline(draw): drawgap() if draw == 1: turtle.pendown() else: turtle.penup() turtle.fd(40) drawgap() turtle.right(90) def drawdigit(digit): turtle.color("gre...
import turtle def drawline(draw): if draw == 1: turtle.pendown() else: turtle.penup() turtle.fd(40) turtle.right(90) def drawdot(): turtle.penup() turtle.fd(10) turtle.right(90) turtle.fd(40) turtle.pendown() turtle.circle(1,360) turtle.penup() ...
# -*- coding: utf-8 -*- """ Created on Mon Mar 25 01:17:56 2019 @author: lasse """ # # Multilayer perceptron with 1 hidden layer. import numpy as np import math # Making a class neuron which holds all the information for each neuron class neuron: def __init__(self, neuron_type, activation_fun = 'sigmoid'):...
limit = int(input()) for i in range(limit+1): print("\n"+str(i)+"\n") for x in range(11): print(str(i)+"x"+str(x)+"="+str(i*x))
import unittest from GameComponents import Board, Player, PlayerPosition, Snake, GreenSnake from GamePlan import GamePlan class TestGamePlan(unittest.TestCase): def setUp(self): self.board = Board() self.player = Player("Test Player") self.player_position = PlayerPosition(self.player.name...
#!/usr/bin/env python # grav.py import math as m def grav(Z,WINDE,WINDN,LAT,LON): """GV = grav(Z,WINDE,WINDN,LAT,LON) ======================================================================= University of Maryland Baltimore County [UMBC] AIRS GRAV ROUTINE NAME: GRAV ...
# создаем f1-метрику (по умолчанию она отсутствует в TF) import tensorflow as tf import numpy as np from tensorflow.python.ops import math_ops from tensorflow.python.keras import backend as K from tensorflow.python.keras.utils.generic_utils import to_list from tensorflow.python.keras import metrics from tensorflow.pyth...
# -*- coding: utf-8 -*- """ Han Ambrose Machine Learning - Vanilla Linear Regression """ import numpy as np import matplotlib.pyplot as plt import math ########################################################################### def read_csv(file): data = list() with open(file, 'r') as f: for li...
import random #List of emojis row1 = ["⬜️","⬜️","⬜️"] row2 = ["⬜️","⬜️","⬜️"] row3 = ["⬜️","⬜️","⬜️"] # Putting the lists into one list map = [row1, row2, row3] # users input print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") # users first number horzi = int(position[0]) # u...
print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") names = name1 + name2 lowercase_Names = names.lower() t = lowercase_Names.count("t") r = lowercase_Names.count("r") u = lowercase_Names.count("u") e = lowercase_Names.count("e") true = t + r + u +...
# Student Height #student_heights = input("Input a list of student heights ").split() student_heights = [180, 162, 171, 201, 153, 155, 181] total_height = 0 number_of_students = 0 for height in student_heights: total_height += height number_of_students += 1 print(total_height) print(number_of_students) averag...
"""A dynamic 2D QuadTree (spatial partitioning tree) The QuadTree has set semantics (duplicate points will be stored once) """ import math from collections import deque X = 0 Y = 1 LOWER_LEFT_QUAD = 0 UPPER_LEFT_QUAD = 1 LOWER_RIGHT_QUAD = 2 UPPER_RIGHT_QUAD = 3 NODE_NOT_IN_REGION = 0 NODE_PARTIALLY_IN_REGION = 1 ...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2017 urbikn <urbikn@knuples.net> # # Distributed under terms of the MIT license. from datetime import datetime class Course: def __init__(self, date = None, time = None, courseName = None, place = None, group = None): self.__...
# -*- coding: utf-8 -*- ''' random ライブラリの利用 ''' import random # 0.0 - 1.0 範囲のフロート値 print(random.random()) # 範囲指定のフロート値 print(random.uniform(15,30)) # 範囲指定のint値 print(random.randint(15,30)) # 引数からの一つの要素 print(random.choice('abcdef')) # リスト要素をシャッフルする # python3 でrangeはイテレータオブジェクトを返す sample_lis...
#!/usr/bin/python import threading main_data=5 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print ("Starting " + self.name) fun...
s = input() letters = set() for letter in s: letters.add(letter) print(1 if len(letters) == len(s) else 0)
# Program structure referred from http://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/ import numpy as np import scipy.io as sio import operator from scipy.spatial.distance import cosine #to compute cosine distance import matplotlib.pyplot as plt # loading the data fr...
print("the power of a given number") M=int(input("number==")) P=int(input("power==")) x=P**M print(x)
print("Enter 'x' for exit."); str1 = input("Enter first string to concatenate: "); if str1 == 'x': exit(); else: str2 = input("Enter second string to concatenate: "); str3 = str1 + str2; print("\nString after concatenation =",str3); print("Str 1 =",str1); print("Str 2 =",str2); print("Str 3 ...
mp=input("enter any character:") if((mp>='a' and mp<='z') or (mp>='A' and mp<='Z')): print(mp,"is an alphapet") else: print(mp,"is not an alphapet")
a=float(input("enter the first number:")) b=float(input("enter the second number:")) sum = float(a) + float(b) print("The sum of given numbers is: ", sum)
def checkDigits(n): while (n>0): if ((n % 10) % 2): return False; n =int(n/10); return True; def largestNumber(n): for i in range(n,-1,-1): if (checkDigits(i)): return i; p =int(input("enter the number:")); print(largestNumber(p));
# -*- coding: utf-8 -*- def my_binarysort(page, a_page, b_page): list_page = [a_page, b_page] count = [0, 0] for i in range(2): start = 1 end = page middle = int((start + end)/2) while(True): if middle > list_page[i]: end = middle ...
#-*-coding: utf-8-*- number = int(input()) number_list = [] if number > 0: for i in range(1, number+1): if number % i == 0: number_list.append(i) print(f'{i}(은)는 {number}의 약수입니다.') if len(number_list) == 2: print(f'{number}(은)는 {number_list[0]}과 {number_list[1]}로만 나눌 수 있는 소수입니다....
T = int(input()) result = [] for t in range(1, T+1): A, B, C, D = map(int, input().split()) if A/B > C/D: result.append('ALICE') elif A/B == C/D: result.append('DRAW') else: result.append('BOB') for i in range(1, T+1): print('#{} {}'.format(i, result[i-1]))
def fact_num(n): if n == 1: fact[n] = 1 elif fact_num(n-1) == 0: return n * fact_num(n-1) else: fact[n] = n * fact[n-1] fact = [0] * 17 for i in range(1, 17): fact_num(i) result = [0] T = int(input()) for _ in range(T):
#-*- coding: utf-8 -*- data = input() data_list = [] final_list = [] result = '' for i in data: data_list.append(i) # 문자열 하나씩 나눠서 리스트로 변환 for j in range(len(data)-1, -1, -1): final_list.append(data_list[j]) for x in final_list: result = result + x print(result) print('입력하신 단어는 회문(Palindrome)입니다.')
""" Problem 1: Rock, Paper, Scissors Break 8:15, 8:30 Problem 2: Fibonacci Start time: 8:10 End time: """ def rps_permutations(number): choices = ["rock", "paper", "scissors"] possibilities = [[] for _ in range(3 ** number)] first_break_index = len(possibilities) // 3 second_break_index = first_break_...
animal = input('Guess an animal') if animal == 'honey badger' : print('Yes you are correct!') else: print('Sorry, wrong animal!')
import numpy as np from matplotlib import pyplot as plt class FisherDiscriminat: """ Calculates the fishers discriminant for two class problem and projects it onto a line """ def __init__(self,X,y): self.w = None self.b = None self.X = X self.y = y self.optimum_w() def optimum_w(self): #the mean f...
import pandas as pd names = pd.read_csv("nato_phonetic_alphabet.csv") # for (letter,word) in names.iterrows(): # print(word.letter,word.code) nato_dict = {word.letter:word.code for (letter,word) in names.iterrows()} # print(nato_dict) while True: usr_name = input("What's your name:") try: res =...
#Write a recursive function to print the factorial for a given number def facto(n): if(n==0): return 1 else: return(n*facto(n-1)) num=int(input("Enter a Number : ")) x=facto(num) print("Factorial of ",num," is ",x)
from linked_list import LinkedList from math import sqrt from random import randrange from typing import List class Graph: def __init__(self, max_v: int): # Initialize the adjacency list for max_v vertices self.adj = [LinkedList() for _ in range(max_v)] # each linked list is a separate object ...
#!/usr/bin/python class SelectionSort(): ''' O(n^2) time complexity. Generally performs worse than insertion sort (except in the worst case for insertion sort, when there is no order to the list). Algorithm: The input list is divided into two parts: An (initially empty) sublist of sorted ite...
#!/usr/bin/env python import sys, math def calculator(): '''Calculate log base 2 of each ratio. Ratios are calculated from adjacent entries from stdin. ''' previous_value = None for line in sys.stdin: line.strip() current_value = float(line) if previous_value and previous_value > 0: ratio = current_...
def bigger(a,b): if a > b: return a else: return b def biggest (a,b,c): return bigger(a, bigger(b,c)) def median (a,b,c): big = biggest (a,b,c) if big == a: return bigger (b,c) if big ==b: return bigger (a,c) else: return bigger(a,b) 7 8 9 a b c if a > b
# -*- coding: utf-8 -*- from tkinter import * import random import time class Ball: def __init__(self, canvas, paddle, score, color): self.canvas = canvas self.paddle = paddle self.score = score self.id = canvas.create_oval(10,10,25,25, fill=color) self.canvas.move(self.id, 245,100) starts = [-3, -2, -1, ...
import sys def moonWeight(initialWeight, increaseNumber, age): print("what is your weight?") initialWeight = int(sys.stdin.readline()) print("what is your increaseNumber ?") increaseNumber = int(sys.stdin.readline()) print("how old are you?") age = int(sys.stdin.readline()) moonWeight = initialWeight * increaseN...
#!usr/bin/env python3 def string_three_numbers_spliter(): a, b, c = [int(i) for i in input('Enter three numbers concatenated ' + 'by a single space between them, e.g. \'3 8 1\': ').split()] return a, b, c def main(): a, b, c = string_three_numbers_spliter() lst = [a, b, c] lst.sort...
count = 0 while True: password = input('Придумайте пароль: ') for i_2 in password: if i_2.isdigit(): count += 1 for i in password: if len(password) >= 8 and i.isupper() and count >= 3: print('Это надёжный пароль!') break else: print('...
string = input('Введите строку: ') count = 1 letters = '' for i in range(len(string)): if string[i] == string[i - 1]: count += 1 else: letters += string[i - 1] + str(count) count = 1 print('Закодированная строка:', letters[2:] + letters[:2])
count_skates = int(input('Кол-во коньков: ')) skates = [] for size_skates in range(count_skates): print('Размер', size_skates + 1, 'пары: ', end='') size_of_pair_skates = int(input()) skates.append(size_of_pair_skates) count_people = int(input('Кол-во людей: ')) legs = [] count_people_skates = 0 for size...
import random import time game_choice = 0 menu_loop = 1 #only values that stay constant outside of the games money = int(1000) roulette_roll = 0 roulette_roll2 = 0 roulette_number = 0 roulette_color = 0 roulette_bet = 0 roulette_title = 1 slots_roll = 0 slots_roll2 = 0 #this is where i...
import NeuronNetworkLibrary.NeuronLayer as nl class NeuralNetwork: def __init__(self, number_layers, list_of_neurons, learningrate = 0.2): """ number of layers [int] - how many layers we want to create list_of_neurons [int] - list of int in which every int present number of neurons in th...
""" タプルとリストの違いは タプル:要素の追加不可 ⇨ 読み込み用 リスト:要素の追加可 タプルにリストを格納することも可能 """ t = (1, 2, 3, 4, 1, 2) print(t) print(type(t)) """ (1, 2, 3, 4, 1, 2) <class 'tuple'> """ print(t[0]) print(t[-1]) print(t[2:5:]) print(t.index(1)) print(t.index(1, 1)) print(t.count(1)) """ 1 2 (3, 4, 1) 0 4 2 """ #print(help(tuple)) t = ([1, 2, ...
l = [1, 20, 4, 50, 2, 1, 2] print(l) print(l[0]) print(l[-1]) print(l[-2]) print(l[0:2]) print(l[:2]) print(l[2:5]) print(l[2:]) print(l[:]) print(len(l)) print(type(l)) print(list('abcdefg')) """ 1 2 1 [1, 20] [1, 20] [4, 50, 2] [4, 50, 2, 1, 2] [1, 20, 4, 50, 2, 1, 2] 7 <class 'list'> ['a', 'b', 'c', 'd', 'e', 'f', '...
s = 'My name is Mike. Hi Mike.' print(s) is_start = s.startswith('My') #指定の文字列で始まっているか print(is_start) print('#############') print(s.find('Mike')) #何文字目に指定も文字列があるか print(s.rfind('Mike')) #何文字目に指定も文字列があるか(後方の文字) print(s.count('Mike')) #指定の文字列が何個入っているか print(s.capitalize()) #先頭の...
l = [1, 2, 3] i = 5 try: l[i] except: print("Don't worry") print("keep proccessing") """ Don't worry keep proccessing """ try: l[i] except IndexError: print("IndexError catch") print("keep proccessing 2") """ IndexError catch keep proccessing 2 """ try: l[i] except IndexError as exc: prin...
class Node(object): def __init__(self, name): self.name = str(name) def getName(self): return self.name def __str__(self): return self.name class Edge(object): def __init__(self, src, dest): self.src = src self.dest = dest def getSource(self): return ...
# -*- coding: utf-8 -*- """ Created on Sat Mar 19 22:11:08 2016 @author: Freeman """ def stdDevOfLengths(L): sum=0 tot = 0.0 for i in L: sum+=len(i) try: mean = sum/float(len(L)) for j in L: tot += (len(j) - mean)**2 return (tot/len(L))**0.5...
from graphics import * import random def printme(str): print(str) def calcme(int1, int2): return int1 * int2 def main(): matrix = [[random.randint(1, 4) for i in range(2)] for i in range(2)] point1 = Point(14, 36) printme(matrix) printme(calcme(matrix, matrix)) main()
def change_making(cents): COINS = [100, 50, 25, 10, 5, 1] num_coins = 0 for coin in COINS: num_coins += cents / coin cents %= coin return num_coins import collections import sys import random # @include PairedTasks = collections.namedtuple('PairedTasks', ('task_1', 'task_2')) def opti...
input1=input() str1 =list(input1) new=[] for j in str1 : if j not in new: new.append(j) cnt=0 for i in range(len(str1)): if j==str1[i]: cnt+=1 print("{}:{}".format(j,cnt))
heads=int(input("No.of heads:")) legs=int(input("No.of legs:")) if legs%2!=0 or heads==0 or heads>legs: print("No solution") else: rab=int((legs+(-2*heads))/2) ch=int(heads-rab) print("{},{}".format(ch,rab))
# Import required libraries import csv # Start a counter and store the textfile in memory gender_counter = {} age_counter = {} lines = csv.reader(open('nyt1.csv')) lines.next() # For each line, fill in the counters for line in lines: age, gender, impressions, clicks, signed_in = line if str(gender) not in g...
class Shape: def __init__(self, w, l): self.width = w self.len = l def print_size(self): print("""{} by {} """.format(self.width, self.len)) class Square(Shape): # 問1 square_list = [] def __init__(self, w, l): self.width = w ...
# MIT 6.034 Lab 7: Support Vector Machines # Written by 6.034 staff from svm_data import * from functools import reduce #### Part 1: Vector Math ####################################################### def dot_product(u, v): """Computes the dot product of two vectors u and v, each represented as a tuple or ...
from logic import ( init_field, is_win, player_step, enemy_step, is_avalible_ceil ) def main(): field = init_field() print_field(field) first_player, second_player = "X", "O" while True: x, y = get_step(first_player) player_step(x, y, first_player, field) print_field(...
import turtle class OlympicTurtle(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self, shape="turtle") screen = turtle.Screen() screen.bgcolor("lightgrey") self.pensize(3) # 设置画笔大小 self.speed(3) # 设置速度 def draw_circle(self, x, y, color, radiu...
"""Module to load data. Consists of functions to load data from four different datasets (IMDb, Rotten Tomatoes, Tweet Weather, Amazon Reviews). Each of these functions do the following: - Read the required fields (texts and labels). - Do any pre-processing if required. For example, make sure all label ...
def bubble_sort(data): for i in range(len(data) - 1): for j in range(len(data) - i - 1): if data[j] > data[j + 1]: temp = data [j + 1] data[j + 1] = data[j] data[j] = temp data = [45,11,2,3,4,99,31,5,4,1,0,0,26,65,459,756,123,45,12,23,453,666,219,...
import time def tripleStepDP(n): if n == 0 or n == 1: return 1 elif n == 2: return 2 counts = [1] * (n + 1) counts[2] = 2 for i in range(3,n + 1): counts[i] = counts[i - 1] + counts[i - 2] + counts[i - 3] return counts[n] start_time = ...
def gcd(a, b): rem = a % b while(rem != 0): a = b b = rem rem = a%b return b print(gcd(20,8)) print(gcd(36,14)) print(gcd(99,11)) print(gcd(173,57))
def is_bst(root_node, min=None, max=None): if root_node is None: return True if root_node.data < min or root_node.data > max: return False return is_bst(root_node.left,min,root_node.data - 1) and is_bst(root_node.right,root_node.data,max)
"""Square Every Digit (Python) def square_digits(num): result = '' for i in str(num): result += f"{int(i) ** 2}" return int(result) Multiples of 3 or 5 (Python) def solution(number): result = 0 for i in range(number): if i % 3 == 0 or i % 5 == 0: result += i r...
# 레퍼런스 복사 import copy a = 1 b = a a = [1,2,3] b = [4,5,6] x = [a,b,100] y = x print(x) print(y) print(x is y) # swallow copy (얕은 복사) a = [1,2,3] b = [4,5,6] x = [a,b,100] y = copy.copy(x) print(x) print(y) print(x is y) print(x[0] is y[0]) # deep copy(깊은 복사) a = [1,2,3] b = [4,5,6] x = [a,b,100] y = copy.deepcop...
num=input().split(" ") a=int(num[0]) b=int(num[1]) print(a+b,end=" ") print(a-b,end=" ") print(a*b)
def main(cook_book): while True: dish = '' dishes = [] person = None print('Блюда в нашей книге : ', cook_book.keys()) dish = input('Введите названия блюд (разделитель запятая)(q - выход) : ') if dish == 'q': return dishes = dish.split(', ') ...
# Functions start with def def my_function(): print("Hello from a function") my_function() def another(a, b): print("My favorite color is " + a) print("My home state is " + b) another("red", "Ohio") def my_home(state = "Ohio"): # With a default value that can be overridden print("I grew up in " + st...
# Simple couroutine which calculates the running average of numbers # There are two examples presented here one without priming and the other one with priming from priming_couroutines import couroutine def calc_average(): average = 0 total = 0 count = 0 while True: value = yield average ...
# Code to understand the inner workings of the islice itertools function # There is nothing special about this, works very similar to the built in slice functionality import itertools values = list(range(2, 21)) print(values) for val in itertools.islice(values, 0, None, 3): print(val)
#name = "Tokunbo" #print (name) #help("keywords") # a = 1 b = 2 print (a + b) x = range(100) for n in x: print(n)
#! python3 # Combines all the pafs in the current working directory into a single pdf import PyPDF2, os, sys, logging class Merge (): """ Merge all pdfs in the current folder, or specific list of files, by name, into a single pdf file """ def __init__ (self, file_output = "", replace = False, d...
import sys from collections import Counter def read_file(filename): c = Counter() d = dict() f = open(filename, "r") lines = f.readlines() for line in lines: left = int(line.split()[0]) right = int(line.split()[1]) c.update([left]) c.update([right]) if left ...
def DigitSum(no): iCnt=0 while(no!=0): iCnt=iCnt+(no%10) no=no/10 return iCnt no=input('Enter a number:') print('Sum of digits:'), print(DigitSum(no))
import sqlite3 as sl def db(): '''inits db, populates table. ''' conn = sl.connect('demo_data.sqlite3') c = conn.cursor() try: c.execute("DROP TABLE demo") except BaseException: c.execute("CREATE TABLE demo (s VARCHAR[1], x INT, y INT);") else: c.execute("CREATE TABLE...
#import library import os import csv #get data path data_path=os.path.join("Resources/02-Homework_03-Python_Instructions_PyBank_Resources_budget_data.csv") #open and read data with open(data_path,'r') as file: #read csv file with delimiter = , csvreader=csv.reader(file, delimiter=',') #get the heade...
""" Q1. (Create a program that fulfills the following specification.) Import Crime.csv File. Perform dimension reduction and group the cities using k-means based on Rape, Murder and assault predictors. """ # PCA # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as ...
""" Q1. (Create a program that fulfills the following specification.) Auto_mpg.txt Here is the dataset about cars. The data concerns city-cycle fuel consumption in miles per gallon (MPG). Import the dataset Auto_mpg.txt Give the column names as "mpg", "cylinders", "displacement","horsepower","weight","acceler...
#conditional judgement 条件控制 guess = eval((input("请输入猜测的数字\n"))) if guess == 99: print("猜对了") else: print("猜错了") print("二分支结构紧凑形式".center(20,"-")) print("猜{}了".format("对" if guess==99 else "错")) print("多分支结构".center(20,"-")) if guess==99: print("猜对了") elif guess>=90: print("数字在90及以上") else: print("...
""" File: anagram.py Name: Isabelle ---------------------------------- This program recursively finds all the anagram(s) for the word input by user and terminates when the input string matches the EXIT constant defined at line 19 If you correctly implement this program, you should see the number of anagrams for each w...
""" File: boggle.py Name: Isabelle ---------------------------------------- The program recursively finds all vocabularies which exist in boggle that program asks user inputs. """ # This is the file name of the dictionary txt file # we will be checking if a word exists by searching through it FILE = 'dictionary.txt' #...
from tkinter import * from tkinter.ttk import Separator from tkinter import messagebox class LisInas: def __init__(self, bd): if bd.isEmptyAlumno(): messagebox.showwarning("Advertencia", "No hay alumnos cargados en la BD.") else: pantalla = Toplevel() pan...
class Parent : parentattr =100 def __init__(self): print("constructor Parent called") def parentmethod(self): print( "calling parent method") def setAttr(self,attr): Parent.parentattr=attr def getAttr(self): print("Parent attribute", Parent.parentattr) ...
class Point: """ Point class manipulates and represents point x, y corodinates""" count=0 #class memebr def __init__(self, x, y ): self.x=x #instance member self.y=y Point.count=Point.count+1 def display(self): print("Point x and y are ", self.x ,' ', self.y) ...
try : print(5/0) except ZeroDivisionError: print("Division by zero occured") except Exception : print("Exception Occured") else : print("In else part") finally : print(" Excecute inspite of exception or no") print("Hello")
x=0 if x<0 : print("Nagative") elif x>0 : print("Positive") else : print("Zero")
s1= "Anil" s2= 'Sunil' s3= "{1} and {0} are friends".format(s1,s2) print(s3) if "A" in s1 : print("A is there in ", s1)
""" Escape Pods =========== You've blown up the LAMBCHOP doomsday device and broken the bunnies out of Lambda's prison - and now you need to escape from the space station as quickly and as orderly as possible! The bunnies have all gathered in various locations throughout the station, and need to make their way towards...
#!/usr/bin/env python3 import re chr_rx = re.compile(r'["\\]') def check_line(text): chars = chr_rx.findall(text) n = 2 + len(chars) return n def solve(problem): return sum(check_line(s) for s in problem.splitlines()) def test(): assert solve(r'""') == 4 assert solve(r'"abc"') == 4 as...
#!/usr/bin/env python3 def solve(problem): return sum(1 if c == '(' else -1 if c == ')' else 0 for c in problem) def test(): assert solve('(())') == 0 assert solve('()()') == 0 assert solve('(((') == 3 assert solve('(()(()(') == 3 assert solve('))(((((') == 3 assert solve('())') == -1 ...
#!/usr/bin/env python3 def check(text): if not any(text[i] == text[i+2] for i in range(0, len(text) - 2)): return False f = False for i in range(0, len(text) - 2): pair = text[i:i+2] if text.find(pair, i + 2) > 0: f = True break if not f: retu...
squares = [] for value in range(1, 11): square = value ** 2 squares.append(square) print(squares) digits = list(range(0, 10)) print(min(digits)) print(max(digits)) print(sum(digits)) squares = [value**2 for value in range(1, 11)] print(squares)
fruits = ['watermelon', 'apple', 'pearl', 'pineapple', 'Kiwi'] print(f"my favorite food is {fruits[:3]}") print(f"my least favorite food is {fruits[-3:]}")