text
stringlengths
37
1.41M
list=[1,2,3,4] it = iter(list) # this builds an iterator object print (next(it)) #prints next available element in iterator #Iterator object can be traversed using regular for statement #!usr//bin/python3 for x in it: print x, ' 3' #or using next() function it = iter(list) while True: try: print (next(it)) ...
frase = ' Curso em Video Python ' print('''\nWhen this began I had nothing to say And I'd get lost in the nothingness inside of me (I was confused) And I let it all out to find that I'm not the only person with these things in mind (Inside of me) but all the vacancy the words revealed Is the only real thing that I've g...
from flask import Flask, render_template, request, redirect import csv app = Flask(__name__) @app.route('/') def home(): return render_template('mountain.html') @app.route('/<string:page_name>') def project(page_name): return render_template(page_name) @app.route('/send_contact_details', methods=['POST']) de...
while True: number = int(raw_input("FizzBuzz Game" '\n' "Select a number between 1 and 100: ")) for count in range(number, 100): if count > 100: break elif count % 3 == 0 & count % 5 == 0: print "fizzbuzz" elif count % 3 == 0: print "fizz" e...
def longest_increasing_array(arr): """ longest sub array in increasing order :param arr: :return: maximum length of sub array """ if not arr: return 0 if len(arr) == 1: return 1 end =1 start = 0 max_len = 1 while end < len(arr): if arr[end] > arr[end -...
'''1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. ''' a = 10 b = 'str' c = 0b10101001 print(f'Если строку - "{b}" умножить на число - {a}, то получится строка\ из {a} "{b}": {b*a}') print("0b10101001 =",...
#coding:utf-8 #Exo_21: x=int(input("Saisir un nombre: ")) for i in range(x): chaine=input("\nSaisissez une texte: ") fichier=open("data.txt","a+") fichier.write("{}\n".format(chaine)) fichier.close() #Exo_22: fichier=open("data.txt","r") ligne = fichier.readlines() for i in ligne: email=i....
# -*- coding: utf-8 -*- __author__ = "Žiga Zupančič" class BTreeNode: def __init__(self, keys=None, children=None, parent=None): self.parent = parent self.children = children if keys is not None: self.keys = keys else: self.keys = [] if self.children...
# -*- coding: utf-8 -*- """Disjoint set""" from typing import Dict, Callable, Tuple from typing import TypeVar T = TypeVar("T") def disjoint_set(dummy: T) -> Tuple[Callable[[T], None], Callable[[T], T], Callable[[T, T], None]]: parent = {} # type: Dict[T, T] rank = {} # type: Dict[T, int] def make_se...
# -*- coding: utf-8 -*- from ..AbstractTree import AbstractTree __author__ = "Eva Erzin" class Node: def __init__(self, key = None, parent = None, left = None, right = None): self.key = key self.parent = parent self.left = left self.right = right def __repr__(self): ...
def binary_calculate(): binary_number = input("Please enter a binary value to convert to decimal: ") for i in binary_number: if i == "0": continue elif i == "1": continue elif i == "-": continue else: print("You can only e...
# triangle numbers! import datetime def sum_divisible_by(number, max): p = int((max - 1)/ number) sum = number * (p * (p + 1)) / 2 return int(sum) def run_program(max): sum = sum_divisible_by(3, max) + sum_divisible_by(5, max) - sum_divisible_by(15, max) print("The sum of all the multiples of 3 or...
# Implement the bubble sort algorithm in the bubble_sort method. # Return the sorted array. # # Helpful Resources # https://www.youtube.com/watch?v=8Kp-8OGwphY # http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBubbleSort.html # def bubble_sort(my_array): swapped = True arrLength = len(my_a...
# Steps # v1 # make 1 array out of 2 (append to end) # sort with insertion sort # v2 # create 3rd array # as pushing values from alternating arrays # compare to other values, # take a1[0] compare to a2[0], insert smaller into a3[0] # take import unittest def merge_arrays_sarahs(a1, a2): merged = [] while ...
import os filenames= os.listdir (".") # get all files' and folders' names in the current directory result = [] for filename in filenames: # loop through all the files and folders if os.path.isdir(os.path.join(os.path.abspath("."), filename)): # check whether the current object is a folder or not result.ap...
import pandas as pd import numpy as np import pickle import streamlit as st from PIL import Image # loading in the model to predict on the data pickle_in = open('classifier.pkl','rb') classifier = pickle.load(pickle_in) def welcome(): return 'welcome all' # defining the function which will make the...
from datetime import date from util import get_date_from_string, make_full_name ALLOWABLE_GENDERS = ('M', 'F') class Athlete: def __init__(self, first_name, last_name, middle, gender, birth_date, team_code, team_name, school_yr="", age=""): self.full_name = make_full_name(first_name, middl...
# Function which calculates the time in days the user (The one who posted # the tweet with tweet id passed as parameter) has been on Twitter, since his # first registration. # Todo: # - Manage exceptions for non existing tweets # - Format the string (created_at) returned by twitter in order to fit in a datetime ob...
# The dictionary will be something like: my_dic = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'], 'Kenneth Love': ['Python Basics', 'Python Collections']} # Often, it's a good idea to hold onto a max_count variable. # Update it when you find a teacher with more classes than # t...
string = "Jordan krueger" def stringcases(string): upper = string.upper() lower = string.lower() title = string.title() reverse = list(string) reverse = reverse[::-1] reverse = ''.join(reverse) print(upper) print(lower) print(title) print(reverse) return (upper, lower, ti...
import threading import time tLock = threading.Lock() def timer(name, delay, repeat): print('Timer: ' + name + ' Started') tLock.acquire() print(name + ' has acquired the lock') while repeat > 0: # tell the timer to wait for a certain amount of time time.sleep(delay) print(name...
from abc import ABCMeta, abstractmethod class Storage(metaclass=ABCMeta): def __init__(self): self.db = None def set_data(self, key, data): self._open() self._store(key.lower(), data) self._close() def get_data(self, key): self._open() data = self._get_da...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int ...
#first python programme wrote by junius # + - * / // % ** # and or not import sys # basic data type myString = 'Hello World' myInteger = 1 myBool = True print (myString,myInteger,myBool) #list and tuple, items in tuple isn't changable #list's operation # append/count/ext...
import os class Node: length = 0 data = 0 def __init__(self,data=0,length=0): self.data=data self.length=length self.lchild=None self.rchild=None def Merge(aTree,bTree): if aTree == N...
import sys import os #input and output stringName = input("please input: ") print (stringName) #new data generate factory #int(), long(), float(), complex() #str(), unicode(), basestring() #list(), tuple()type() dict() #bool()set(), frozenset() #object()classmethod() #staticmethod()super() #property()file...
import os def shellSorting(aList): distance = int(len(aList)/2) while distance > 0: i = distance + 1 while i < len(aList): t1 = aList[i] j = i - distance while j > 0: t2 = j + distance print ("compare",aList[...
import enum import turtle SCREEN_WIDTH = 800 SCREEN_HEIGHT = 800 class Direction(enum.Enum): Up = 90 Down = 270 Left = 180 Right = 0 def draw_score(pen: turtle.Turtle): pen.penup() pen.goto((-(SCREEN_WIDTH/2)+10, (SCREEN_HEIGHT/2)-40)) pen.pencolor("white") pen.pendown() pen.write("SCORE: ", font=(...
import re def get_artist_name_formated(name_artist: str): """Return the name of the artist formated Args: name_artist (str) Returns: str: name of the artist """ result_regex = re.findall('[a-zA-Z0-9]', name_artist) result_regex = ''.join(result_regex) return result_regex....
import re import logging import time """ Copyright: @2019 Author: Zweli Mthethwa """ # create and configure logger logging.basicConfig(filename = "logs/string_calculator.log", level=logging.DEBUG, format="%(asctime)s %(message)s") logger = logging.getLogger() class StringCalculator(): """This class has functions t...
import pygame pygame.init() screen = pygame.display.set_mode((640, 320)) # set screen size pygame.display.set_caption('screen') # set screen name clock = pygame.time.Clock() FPS = 60 moving = False screen.fill((255,255,255)) pygame.draw.circle(screen,(0,0,0),((screen.get_width()/2),(screen.get_height()/2)),10,0) ...
import threading # When creating threads, add them to this list list_Of_Threads = [] # Function that appends thread to list def append_Thread(thread): list_Of_Threads.append(thread) # function thread to check if threads are alive def thread_Check(): # checker if a thread died error_Check = False #...
# This was my solution submitted and passed all the test cases ''' Author: Ashutosh Srivastava Python3 solution ''' def solution(h, q): return [parent(h,x) for x in q] def parent(h,i): depth = (2**h)-1 res = -1 if(depth<=i): return res else: breaker = True subtree = depth ...
''' Author: Ashutosh Srivastava Python3 solution ''' import math dict_main={} def cal(N): if N in dict_main: return dict_main[N] elif N not in dict_main: if(N%2==0): dict_main[N]=0 return 0 else: flag=0 for i in range(3,int(math.sqrt(N)...
#data type: integer, floating name='Sam' last_letters=name[1:] print(last_letters) x='hello world' x=x + " it is beautiful outside" print (x) print (x.upper()) print (x.split()) #strings,format print ('This is a string {}'.format('inserted')) print('the {} {} {}'.format('fox','brown','quick')) print('The {f} {f} {f}'....
from functools import reduce def read_notes(filename): with open(filename) as f: t, schedule = f.read().splitlines() return int(t), [None if bus == "x" else int(bus) for bus in schedule.split(",")] def problem1(t, schedule): waiting_times = [((int(t / bus) + 1) * bus - t, bus) for bus in sch...
def run(filename): with open(filename) as f: instructions = f.read() n = 0 first_basement_instruction = 0 for i, instruction in enumerate(instructions): if instruction == "(": n += 1 else: n -= 1 if n == -1 and not first_basement_instruction:...
# Questão 2: Escreva um programa que imprima uma pirâmide de números se- gundo o exemplo abaixo: # # Exemplo: # Entre com o numero de linhas da piramide: 5 # 1 # 1 2 # 1 2 3 # 1 2 3 4 # 1 2 3 4 5 # # Exemplo: # Entre com o numero de linhas da piramide: 8 # 1 # 1 2 # 1 2 3 # 1 2 3 4 # 1 2 3 4 5 # 1 2 3 4 5 6 # 1 2 3...
# # def list_benefits(): # # return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together" # # # # # Modify this function to concatenate to each benefit - " is a benefit of functions!" # # def build_sentence(benefit): # # return "%s is a benef...
# Put your app in here. from flask import Flask, request, redirect from operations import add, sub, mult, div app = Flask(__name__) @app.route('/') def home(): html = """ <html> <body> <h1>Do some Math</h1> <form method="POST"> <select name="operation" > ...
"""Interface for an Observer of a game being refereed in Santorini.""" from abc import ABC, abstractmethod class AbstractObserver(ABC): """Interface for a Observer object in Santorini.""" def __init__(self, referee): """Create an observer object that plugs into the referee The method...
class InvalidFormulaException(Exception): """Exception raised for errors in the JSON formula""" def __init__(self): self.message = "Invalid formula." class Spreadsheet: """ Represents a spreadsheet. A rectangular, indexed arrangement of formulas is stored as a dictionary in the field 'dat...
"""Interface for a referee in Santorini.""" from abc import ABC, abstractmethod class PlayerResult(Enum): """ Describes a result of a player interaction """ OK = 0 GIVE_UP = 1 BAD = 2 NEFARIOUS = 3 class AbstractReferee(ABC): """Interface for a Referee component in Santorini.""" def __ini...
import sys import json def parse_json(in_str): """ Takes a json in String form and parses it. in_str: String, input json with multiple lines return: String, the json values in reverse position on separate lines embedded in a json array indicating the reverse position. ...
from turtle import Screen, Turtle from tkinter import * from math import sqrt import hangmanmodel from pynput import keyboard from pynput.keyboard import Key import turtle import random from alphabet import alphabet canvas = Screen() inp = simpledialog.askstring("Input", "What is your word?", parent=canvas....
""" This file is for List and 1D np array Manipulations. For matrix manipulation and dict manipulation, see DataParser.py. """ import numpy as np import CCDLUtil.Utility.AssertVal as AV def extract_min_difference_in_list(lst): """ Takes a list and extracts the minimum difference between consecutive items. ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt path = r'C:\Users\Ted\Desktop\data\数据集.txt'#用显示声明字符串不用转义()加r data = pd.read_csv(path, header=None, names=['Population','Profit']) data.head() data.plot(kind='scatter', x='Population', y='Profit', figsize=(8, 4)) def computeCost(X,y,theta): ...
import random def roll(inStr): """ Rolls a die roll formula. Returns the total and a list of dice rolls as a tuple. To roll with advantage, include an '*'. To roll with disadvantage, include an '_'. Example inputs: '8d6', '1d20*+3', '1d20_-1', '1d20+1d4+2', '1d20-1d6+1' """ # Split input string into a list of d...
def adds(x,y): sums = x+y print(sums) adds(4,5) def subtract(x,y): subs = x-y print(subs) subtract(10,4) def multiply(x,y): mul = x*y print(mul) multiply(4,6) def divison(x,y): div = x/y print(div) divison(10,5)
# -*- coding: utf-8 -*- """ Created on Sun Feb 2 11:24:42 2014 @author: Dennis Chen """ # you may find it useful to import these variables (although you are not required to use them) from amino_acids import aa, codons def collapse(L): """ Converts a list of strings to a string by concatenating all elements of t...
import ipaddress import csv import unittest class Firewall: def __init__(self, csv_path): self.__rules = [] with open(csv_path, encoding='utf-8-sig') as csv_file: csvr = csv.reader(csv_file) for line in csvr: self.__rules.append(line) ...
# 1D ARRAY # 7/11/17 # DECLARE Ages : ARRAY(0..9) OF INTEGER Ages = [] for index in range (0,10): num = int(input("enter a number between zero and 10")) while num > 10 or num < 0: print("error - not within range") input("enter a number between 0 and 10") Ages.append(num) #Ages = [3,4,5,88,45,12,36,48,40,89]...
def validacion(mensaje): nb = input(mensaje) isvalid0 = False while not isvalid0: if nb[1:].isdigit(): nb = int(nb) isvalid0 = True else: print(nb, 'debe ser un número entero') nb = input(mensaje) return nb nb_a = validacion(...
from es_decimal_positivo import esDecimalPositivo import screen def valid(message): nb_str = screen.Input(message, row = 1, col = 1) while not esDecimalPositivo(nb_str): screen.Print('Input Inválido: ' + nb_str + ' debe ser un número positivo', row = 25, col = 1, style = 'bold', colo...
import re ############################## # CLEAN TEXT ############################## mediaPattern = r"(\<Media omitted\>)" # Because it serves no purpose regexMedia = re.compile(mediaPattern, flags=re.M) dateAndTimepattern = r"(\d+\/\d+\/\d+)(,)(\s)(\d+:\d+)(\s)(\w+)(\s)(-)(\s\w+)*(:)" regexDate = re.compile(dateAnd...
x =int(input("entrer une valeur")) r = x % 2 if r== 0: print("x est un nombre pair" ,r) else: print(" x est un nombre impair" )
import time from threading import Timer time.sleep(2) print("press the 'enter' key as fast as you can to continue breaking the turret!!") timeout = 7 t = Timer(timeout, print, ['Sorry, you were too slow! You died before you got the turret']) t.start() print("You have %d seconds to break the turret...\n" % timeout) ...
from Linked_List import Linked_List class Deque: def __init__(self): self._list = Linked_List() def __str__(self): return str(self._list) def __len__(self): return len(self._list) def push_front(self, val): new = Linked_List._Node(val) if len(sel...
import math t = 0 a = 0 d = float(input("d=")) d = (9.8*a**2+5.52*math.cos(t**5)) print(d)
#!/usr/python #Inputs #string1 = input("Enter your first string of DNA seq here: ") #string2 = input("Enter your second string of DNA seq here: ") large_dataset = open('C:\Bachelor Bioinformatik\Bachelor Bioinformatik\ProPra\RosalindBioinfoStronghold\HammingDistance.txt').read() s, t = large_dataset.split() ...
#!/usr/python n = int(input("Enter your number of months here please: ")) k = int(input("Enter your number of off-springs/subunits here please: ")) def Fibonacci_Rabbit(n,k): if n <= 0: print("Incorrect input") elif n == 1 and 0< k <= 5: return 1 elif n == 2 and 0< k <= 5: ...
#!/usr/python3 string = input("Enter your string here: ") a = int(input("Your a value: ")) b = int(input("Your b value: ")) c = int(input("Your c value: ")) d = int(input("Your d value: ")) if 1 <= len(string) <= 200: first_substring = string[a:b+1] second_substring = string[c: d+1] print(fir...
import threading from time import sleep, ctime # 从Thread类派生的子类 class MyThread(threading.Thread): # 重写父类的构造方法,其中func是线程函数,args是传入线程函数的参数,name是线程名 def __init__(self, func, args, name=''): # 调用父类的构造方法,并传入相应的参数值 super().__init__(target=func, name=name, args=args) # 重写...
import csv with open('files/data.csv', 'r', encoding='utf-8') as f: reader = csv.reader(f) for row in reader: print(row) import pandas as pd df = pd.read_csv('files/data.csv') print(type(df)) print(df)
import random from time import sleep import _thread as thread # start_new_thread方法的第二个参数可以为线程函数传递参数,类型必须为元组 # 线程函数,其中a和b是通过start_new_thread函数传入的参数 def fun(a, b): print(a, b) # 随机休眠一个的时间(1到4秒) sleep(random.randint(1, 5)) # 启动8个线程 for i in range(8): # 为每一个线程函数传入2个参数值 thread.start_new_thread(fun, ...
# Given an array of integers, every element appears twice except for one. # Implement a program that will print that single one. # Example: [1,1,2,2,3,3,4,5,5,6,6,7,7] - 4 would be the odd man out # Note: # Your algorithm should have a linear runtime complexity. # *** your code here *** dd = {} def find_odd(my_l...
#!/bin/python3 # HackerRank # Problem: Hashmaps Count Triplets # Status: In process import math import os import random import re import sys # Complete the countTriplets function below. def countTriplets(arr, r): result = 0 all_val = dict() for i, item in enumerate(arr): if item not in all_val: ...
from datetime import datetime from utils_dates import split_date_range class JobHistorySummary: def __init__(self, graduation_date=None, job_positions_data_ranges=None): self.had_job_while_studying = False self.had_job_after_graduation_within_3_months = False self.had_job_after_graduatio...
''' Alunos: Gabriel Ferreira Cavalhieri - RA: 21515695 João Lucas de Souza Yonéa - RA: 21598575 Roberta Ferreira Duprat - RA: 21551006 ''' lista = [] dadoscadastro = [] def cadastrar(): #função para a opção 1 cadastro = {} cadastro["nome"] = input("Insira o nome do Usuário: ") cadastro["e-mail"] = input("...
mts = float(input("Digite a metragem desejada: ")) cm = mts * 100 print("A medida em centimetros é de " + str(cm) + " cm")
from math import ceil mts = float(input("Digite a metragem de parede: ")) qtdLitros = mts / 3 numLatas = ceil(qtdLitros / 18) preco = numLatas * 80 print("Voce devera comprar", numLatas, "lata e pagara", preco, "reais")
sal = float(input("Digite o valor que tu ganha por hora: ")) hrs = float(input("Digite quantas horas tu trabalhou neste mes: ")) salBruto = sal * hrs impRenda = salBruto * 0.11 inss = salBruto * 0.08 sind = salBruto * 0.05 salLiq = salBruto - (impRenda + inss + sind) print("+ Salário Bruto : R$ " + str(salBruto)) prin...
a = int(input()) b = int(input()) print(a if a>b else b) print(b if a>b else a)
# write your code here a = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] print(f""" --------- | {a[0]} {a[1]} {a[2]} | | {a[3]} {a[4]} {a[5]} | | {a[6]} {a[7]} {a[8]} | ---------""") num_turns = 0 result = False pos = ["11", '12', '13', '21', '22', '23', '31', '32', '33'] vic_pos = [[a[0], a[1], a[2]], ...
# 10-1 예외처리 : 에러가 발생했을 때 그에 대한 처리 try: # try내에 ValueError나 ZeroDivisionError가 있을 경우 해당except항목을 실행 print("나누기 전용 계산기입니다.") num1 = int(input("첫 번째 숫자를 입력하세요.")) # 첫 번째 숫자를 입력하세요.숫자입력 num2 = int(input("두 번째 숫자를 입력하세요.")) # 두 번째 숫자를 입력하세요.숫자입력 print("{0} / {1} = {2}".format(num1, num2, int(num1/num2))) exc...
import string # Please not that the key is generated only using lowercase letters # Provide the starting letter and whether you need decode key (decodeflag == True) or encode key (decodeflag == False), # this function will return the key (either for decode or encode). def generate_key(start_letter, decodeflag): ...
from random import random,randint import math import matplotlib.pyplot as plt """ initialise une liste de paramètres de bernoulis aléatoirement On l'utilise comme la liste des machines """ def initmu(n): mu = [] for i in range(n): mu.append(random()) return mu T = 80 # nb de partie à jouer CONSTANT...
# sortowanie bombelkowe #lista [2,7,1,3] lista = [2,7,1,3,5,8,0,10] print lista #print len(lista) koniec = 1 zmiana = 0 while (koniec): for i in range(0, len(lista)-1): print lista[i] print lista[i+1] if (lista[i] > lista[i + 1]): #print i temp = lista[i + 1] ...
""" Napisac skrypt ktory pyta nas o: 1. ilosc wszystkich PRek: 2. ilosc Fail A 3. ilosc Fail B 4. ilosc Fail S i drukuje % wszystkich prek i fail S/A/B """ Total_PRs = raw_input("What is the total number of PRs? -->") Failed_S_PRs = raw_input("What is the number of failed S PRs? -->") Failed_A_PRs = raw_inpu...
""" Napisac skrypt ktory pyta nas o: 1. ilosc wszystkich PRek: 2. ilosc Fail A 3. ilosc Fail B 4. ilosc Fail S i drukuje % wszystkich prek i fail S/A/B """ while True: while True: Fail_A=1 Fail_B=1 Fail_S=1 Fail_all=1 print "podaj liczbe PR klasy A wprowadzonych do...
"""This module performs the following steps sequentially: 1. Reads in existing account IDs (if any) from the bank database. 2. Creates additional accounts with randomly generated IDs. Then, it adds a bit of money to each new account. 3. Chooses two accounts at random and takes half of the money from the fi...
new_dict = {'llave1': 'hola', 'llave2': [1, 3, 5, 97], 'llave3': {'key1': 1, 'key2': 2, 'key3': 3}} llaves = [''] print(new_dict['llave3']['key2']) new_dict['llave2'].append(55) print(new_dict['llave2']) new_dict['llave4'] = 'otro valor' print(new_dict) new_dict['llave3']['key4'] = 4 print(new_dict['llave3']) ...
#Since, data stored in shelf is in key-value form, just like dictionary, shelf has keys() & values()- that will return list like values of keys & values #But not actual list is returned, Hence to get in form of list, use list() #First Saving multiple objects to shelf file import shelve listOfPlayers = ['conor', 'jon', ...
#Dictionary is a collection of key-value pairs, enclosed within {} #Each key in dictionary is associated with some value. They are sometimes called Associative Arrays becus each key is associated with some value #Unlike lists, dictionary elements are not accessed via some offset value(only integers starting with 0), th...
#A file has two key properties: a filename and a path. The path specifies the location of a file on the computer. #For example, a file on Windows OS present in D drive, in folder Demo , filename is - test.py , the path will be - D:\Demo\test.py #The part of the filename after the last period is called the file’s extens...
#Sorting Python dictionary using built-in sorted() #sorted() - returns list of values which have been sorted (aescending order by default) #sorted(dictionary-name) - return a sorted list of keys teams = {4:'PSG', 2:'Barcelona', 5:'madrid', 3:'Chelsea', 8:'arsenal', 6:'manchester'} sortByKey = sorted(teams) print(sortB...
#An expression with two strings joined using in or not in will evaluate to a Boolean True or False. #These expressions test whether the first string (the exact string, case sensitive) can be found within the second string. name = "Hello World!" print('Hello' in name) #True print('hello' in name) ...
#A file containing set of functions, which you want to include in your application. #Module is nothing but a file containing python code. To break larger coder in smaller manageable & organized code #Modules help in organizing our code, makes code easy to maintain & place similar code at one place according to their fu...
fruits = ('apple', 'orange', 'mango', 'plum', 'grapes') #using for loop , to loop over any tuple for f in fruits : print(f, end=' ') #apple orange mango plum grapes print() #using enumerate() to loop over both index & its element """ apple present at index 0 orange present at index 1 mango prese...
#To read a file - file_object = open(filename, mode), open() returns a file object that represents file & its contents #Different modes in which you can open a file is - 'r' - reading mode(default mode), 'w' - writing mode, 'a' - append mode, 'r+' - read/write mode (file pointer at begining of file), 'a+' - append & re...
#You can filter elements of a list or dictionary using filter() and lambda function #filter(function, list) takes 2 arguments one is functions that returns True if certain condition gets true, while 2nd argument is a list to process li = [5, 12, 7, 97, 100, 60, 17] #1st arguments is a lambda function that returns bool...
import random import string #To generate random string of length 5 of only lowercase letters list = string.ascii_lowercase randomString = '' for i in range(5) : randomString+=random.choice(list) print('Random string is : ' + randomString) #Random string is : nqsyf #To generate random string of...
#syntax : if (some condition that evaluates to either True or False) : #block of code # else : #block of code #if condition in if is True, then run if-statement, else run else block #else part is optional in if-else statements name = 'audi' if name == 'audi' : print('this is ...
#Using iterators with dictionary d = {'a':1, 'b':5, 'c':9} for k in d : print(k, d[k]) """ a 1 b 5 c 9 """ I = iter(d) print(next(I)) #a print(next(I)) #b #Using iterators with range()...
#while loops make a block of code execute over and over again as long as condition in while is True #while (some condition) : //block of code #this will print 'spam' 5 times spam = 0 while spam<5 : print('spam ' + str(spam)) spam = spam + 1 #You can see, by default print() prints everytime in new line when cal...
result = [] path = [] last = -1 def printLIS(a): global last b = [] i = last while i != -1: b.append(a[i]) i = path[i] for i in range(len(b) - 1, -1, -1): print(b[i], end=' ') def lower_bound(a, sub, n, x): left = 0 right = n pos = right wh...
class Time: def __init__(self, date = 0, month = 0, year = 0): self.day = date self.month = month self.year = year def check_last(self, other): return self.year > other.year or (self.year == other.year and (self.month > other.month or (self.month == other.month and self.day > ot...
def binarySearch(a, left, right, x): while (left <= right): mid = (left + right) // 2 if x == a[mid]: return mid elif x < a[mid]: right = mid - 1 else: left = mid + 1 return -1 t = int(input()) for i in range(t): n, m = map(int, input().s...
class Edge: def __init__(self, u = 0, v = 1): self.i = u self.j = v def __str__(self): s = "{0} {1}".format(self.i, self.j) return s n = int(input()) adjacent_matrix = [] flag = True for i in range(n): arr = list(map(int, input().split())) adjacent_matrix.append(arr)...
n = int(input()) arr = list(map(int, input().split())) def checkFashion(array): count_0 = 0 if (len(array) == 1): if (array[0] == 1): print("YES") return else: print("NO") return for i in range(len(array)): if (array[i] == 0): ...