text
stringlengths
37
1.41M
import random # minus print('minus') a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = [2, 5, 7] c = [item for item in a if item not in b] print(c) # add print('add') a = [1, 2, 3] b = [3, 4, 5, 6] c = a + b print(c) # shuffle print('shuffle') a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(a, 5) print(slice) # shuffle...
# Skyline.py by Dave Musicant # Note from Adam Canady - this code was used to test the class in building.py from building import * from graphics import * def main(): # Create a window object and make it appear windowWidth = 800 windowHeight = 500 window = GraphWin('Skyline',windowWidth,windowHeight) ...
# input.py # Written by Dave Musicant # This program demonstrates how to accept input from the user. currentString = raw_input('What is the current year? ') currentyear = int(currentString) birthString = raw_input('In what year were you born? ') birthyear = int(birthString) difference = currentyear - birthyear prin...
import math import turtle import random """ This program draws arrows randomly in a box. Author: Sanchit Monga language: python """ """ declaring global variables that will be used throughout the program """ MAX_SIZE=30 MAX_DISTANCE=30 MAX_ANGLE=30 BOUNDING_BOX=100 MAX_FIGURES=500 """ This function calculates and retu...
""" author:Sanchit Monga Lang: Python Purpose: This program performs various operations on the nodes """ from linked_code import LinkNode as Node import linked_code def convert_to_nodes(dna_string): """ This function takes the string as the input and convert it into the node data structure """ if(dna_string=="...
import sqlite3 db = sqlite3.connect("myshop.db") cursor = db.cursor() cursor.execute('SELECT * FROM Customer order by Town') for row in cursor: print '-'*10 print 'ID:', row[0] print 'First name:', row[1] print 'Second name:', row[2] print '-'*10 cursor.close() db.close()
#!/usr/bin/env python # coding: utf-8 # In[2]: #Introduction: #Pandas is a Python library. #Pandas is used to analyze data. #Why Use Pandas? #Pandas allows us to analyze big data and make conclusions based on statistical theories. #Pandas can clean messy data sets, and make them readable and relevant. #Relevant data...
fname = input("Enter file name: ") if len(fname) == 0: fname = 'romeo.txt' fh = open(fname) lst = list() # Iterates through each line in filehandle for line in fh: #Iterates through each word on line for i in line.split(): #Checks to see if word is already in list if not i in lst: ...
## link = https://leetcode.com/problems/minimum-path-sum/ """ 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. """ grid = [[1,3,1],[1,5,1],[4,2,1]]...
## https://leetcode.com/problems/2-keys-keyboard/ """ There is only one character 'A' on the screen of a notepad. You can perform two operations on this notepad for each step: Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). Paste: You can paste the characters which ar...
## https://leetcode.com/problems/coin-change/ """ You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any comb...
""" 1. It finds the least elememt from the array and swap it with the first index element. 2. In sort algo 3. Not Stable """ arr = [8,77,4,1,6,2,7,-8] n = len(arr) ## method 1(Unstable Sort) for i in range(n): min_index = i for j in range(i+1,n): if arr[j] < arr[min_index]: min_index = j ...
#0.030 Class and Static Method Coding from datetime import datetime, timezone, timedelta class Timer: tz = timezone.utc #for all instance of class timer the time must be #the same time zone where program is running. @classmethod def set_tz(cls, offset , name): cls.tz = timezone(timedel...
#********Deleting Attribute in Class******* class MyClass: language = 'python' version = '3.6' print(MyClass.version) #Output:- 3.6 #*******delattr delattr(MyClass, 'version') print(MyClass.version) #Output:- Exception
#0.024.1 Read Only Properties Conti #Caching Computed Property ''' Using Property setters is sometimes useful for controlling how other computed properties are cached. ''' ''' In Our Last program:- Circle :- is a class -->area :- is a computed property -->lazy computation :- only calculate are...
#********Setting Attribute in Class******* class MyClass: language = 'python' version = '3.6' print(MyClass.version) #Output:- 3.6 #setattr function setattr(MyClass,'version','4.2') print(MyClass.version) #Output:- 4.2 print(getattr(MyClass, 'version')) #Output:- 4.2 #We...
#Function Attribute - Instance Methods ''' When we call a function which is inside a class , But from the instance. It Becomes a method. Which is function bound to perticular instance. That allows us inside the function body to use the state of perticular instance , that was passed in. ''' ''' We have to ...
class MyClass: pass my_Obj = MyClass print(my_Obj) #<class '__main__.MyClass'> my_Obj = MyClass() #Calling MyClass print(my_Obj) # It will create an object of MyClass #<__main__.MyClass object at 0x0000022445CEE6D8> print(type(MyClass)) #type of class is type #<class 'type'> print(type(my_Ob...
# -*- coding:utf-8 -*- import numpy as np import matplotlib.pyplot as plt plt.figure(1) #创建图表1 plt.figure(2) #创建图表2 ax1 = plt.subplot(211) # ax2 = plt.subplot(212) x = np.linspace(0,3,100) for i in xrange(5): plt.figure(1) #选择图表1 plt.plot(x,np.exp(i*x/3)) plt.sca(ax1) #选择图表2 的子图1 plt.plot(x,np.sin(i*x)) plt.s...
# 1 kyu # Mine Sweeper # https://www.codewars.com/kata/mine-sweeper/python import numpy as np import queue from itertools import permutations class Minefield: def __init__(self, minefield, number_of_bombs): self.minefield, self.starting_positions = self.parse_map(minefield) self.n = number_of_bom...
def solution(numbers): answer = 0 for i in range(1,10): if i not in numbers: answer += i return answer print(solution([1,2,3,4,6,7,8,0])) print(solution([5,8,4,0,6,7,9]))
#o comando 'from' pode serusado para chamar um arquivo python e o comando 'import' pode chamar todo o arquivo ou somente #um módulo ou definição ('def') para este caso usa-se o 'from' antes. Lembrando de usar o comando 'main'(if __name__ == '__main__':) # no arquivo origem para chamar a classe from aula7_televisao imp...
#trabalhando com APIs. a biblioteca 'request' é: Requests is an elegant and simple HTTP library for Python #o commando '.get' é usado para obter os dados do local citado entre ( ) import requests def retorna_dados_cep(cep): response = requests.get('http://viacep.com.br/ws/{}/json/'.format(cep)) print(response....
def remove_element(nums, val): i = 0 while i < len(nums): if nums[i] == val: del nums[i] else: i += 1 return len(nums) print(remove_element([0,1,2,2,3,0,4,2],2)) #5
# = in python means assigning a number. so when dealing with operators and you want to mean equal to alone you use double equal to signs # e.g. d=1 e=2 print(d==e) # inequality operator print(d !=e) # comparison operators are used with conditional statements which are 'if' statements # Logical operators # and - a...
#Alfredo velasquez. P1E2. CONVERTIR DE CENTRIGRADOS A FAHRENHEIT c = float(input('Introduce los grados centigrados: ')) f = c*(9/5)+32 print('Son %f grados fahrenheit' % f)
def make_sqaure(size): pass def make_rectangle(length, width): pass def make_triangle(size): pass def main(): while(True): print('Hello, please enter what to print') print('1\tsquare') print('2\trectangle') print('3\ttriangle') shape = (int)(input('Input: ')) ...
def insertionSort(b): for i in range(1, len(b)): up = b[i] j = i -1 while j >= 0 and b[j] > up: b[j+1] = b[j] j -= 1 b[j + 1] = up return b def bucketSort(x): arr = [] slot_num = 10 for i in range(slot_num): arr.append([]) # ...
#Reandom number guesser program import random n = random.randint(1,100) chance = 3 while(chance): print("Guess a number") num = int(input()) if(chance != 1): if(num == n): print('Hola You have guessed the right number!!!!') elif(num > n): print("You are a little hig...
# 행맨 게임 import random words = ["apple","coffee","guitar","harmony","programmers","spaghetti"] question = random.choice(words) letters = "" print("-"*50) print("Welcome To Hangman Game") print("-"*50) life = len(questions) + 2 while True: answer = True for w in question: if w in letters: print(w, end...
# Binomial Dist #para atma problemi: # p = olasilik = 0.5 # n = deneyin gerceklestirilme sayisi # tura = p # yazi = 1-p '''para 6 kere atiliyorsa 3 tura cikmasi maksimum olasilik, 1 tura 5 yazi cikmasi minimum olasilik''' from scipy.stats import binom import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) x...
#Time complexity: O(n+k) where n is the number of elements in input array #and k is the range of the input #Auxiliary Space: O(n+k) #The main problem with this counting sort is that we cannot sort the elements #if we have negative numbers in it. Getting around that requires storing the #count of the minimum element at...
def fact(n): out = 1 for i in range(1, n + 1): out = out * i return out def combination(m, n): res = fact(m) / (fact(m-n) * fact(n)) return int(res) def pascal_row(n): out = [] for i in range(n+1): temp = combination(n, i) out.append(temp) return out def p...
# r --> readable # w --> writeable # a --> append # t --> text # b --> bytes # + f = open("output.txt", mode='r+') # text = f.read() f.seek(10, 2) f.write("hello") # print(text)
class Positives(object): def __init__(self): self.current = 0 def __next__(self): result = self.current self.current += 1 return result def __iter__(self): return self counts = [1, 2, 3] for item in counts: print(item) i = iter(counts) try: while True: ...
def fib(n): if n == 1: return 0 elif n == 2: return 1 else: return fib(n-1) - fib(n-2) print(fib(3)) def memo(f): cache = {} def memoized(n): if n not in cache: cache[n] = f(n) return cache[n] return memoized fib = memo(fib) fib(40) class Rl...
# C = (F - 32) * 5/9 # Run F input to C output def C_temp(): F_degree = int(input('How many degrees in Fahrenheit? ')) C_degree = float(F_degree - 32) * (5/9) return C_degree print(str(C_temp()) + 'C')
#Time complexity O(n) and space complexity O(n) # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: #In...
# -*- coding: utf-8 -*- """ Created on Thu Jun 08 19:13:27 2017 @author: Administrator """ import math def is_prime(x): flag = 0 i = int(math.sqrt(x)) for j in range(1,i+1): if (x % i == 0): flag = 0 break if (j >= i): flag = 1 return flag """ Attention you must put n and x outside the loop,or I will not get t...
from utils import * import time class Result(): """ Class which carries the results of an experiment. It contains data such as the dimension of the problem, and has a callback that can be placed into an iterative algorithm so it collects results and data in real time. Usage: result = Resu...
import turtle a = 5 print (a) b = 'hello' print(b) credit_card = 357238952792 print(credit_card) qazi_turtle = turtle.Turtle() qazi_turtle.speed(30) def square(): qazi_turtle.forward(100) qazi_turtle.right(90) qazi_turtle.forward(100) qazi_turtle.right(90) qazi_turtle.forwa...
# This is a working prototype. DO NOT USE IT IN LIVE PROJECTS class KalmanFilter: def __init__(self, r, q, a=1, b=0, c=1): # R models the process noise and describes how noisy a system internally is. # How much noise can be expected from the system itself? # When a system is constant R can be set to a (very) lo...
__author__ = '619635' my_age=input("Enter your age:") print("After one year, your age will be " + str(int(my_age)+1) )
__author__ = '619635' n=int(input("Eneter number")) for i in range(0,1000,n): print(i) #Priniting values in reverse for i in range(10,-1,-1): print(i)
__author__ = '619635' import random num=random.randint(1,10) while True: provideinput=int(input("Please provide your input\n")) if provideinput > num: print("your number is higher than the guess number\n") elif provideinput < num: print("your number is smaller than the guess nu...
__author__ = '619635' for i in range(0,100): if i%2 == 0: print(str(i) + ' is even') else: print(str(i) + ' is odd')
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> l=[1,2,3,4,5,6] >>> l [1, 2, 3, 4, 5, 6] >>> type(l) <class 'list'> >>> print(type(l)) <class 'list'> >>> id(l) 1625530265408 >>> l.appen...
def check_baggage(baggage_weight): try: if(baggage_weight >= 0 and baggage_weight < 40): return True else: return False except TypeError: print("INVALID baggage weight entered") def check_immigration(expiry_year): try: if(expiry_year >= 2001 and expir...
#Python Program to find Bill Amount after discount and Validate Bill Amount bill_amount = int(input("Enter Bill Amount:")) customer_id = int(input("Enter User ID:")) if(customer_id in range(100,1001)): if(bill_amount >= 1000): bill_amount_discounted = bill_amount - (bill_amount * (5/100)) elif(bill_am...
with open('courses.txt','r') as inFile: content = inFile.readlines() print("File Content : ") dictionary = dict() array =list() i = 0 for line in content: line=line.strip() print(line) dictionary[i] = line array.append(line) i += 1 print("Dictionary :",end=' ') print(dictionary) print("List ...
def check_baggage(baggage_weight): if baggage_weight >= 0 or baggage_weight <= 40: return True else: return False def check_immigration(expiry_year): if expiry_year >= 2001 or expiry_year <= 2025: return True else: return False def check_security(noc_status): if n...
with open('student_details.txt','r') as inFile: content = inFile.readlines() list_of_list=list() list_of_dictionary=list() i =0 for line in content: line = line.strip() print(line) item = line.split() list_of_list.append(item) d = dict() d[item[0]]=item[1] list_of_dictionary.append(...
# -*- coding: utf-8 -*- """ Created on Thu Dec 13 21:18:49 2018 @author: Haile """ # Dependencies- modules to read csv and create file paths import csv import os # Loading election data csv and path for the result file csvpath_elec = os.path.join("Resources", "election_data.csv") csvpath_elec_result_output = os.path...
#!/usr/bin/env python def is_substring(s1, s2): return s1 in s2 def is_rotated(s1, s2): common = s1[len(s1) / 4:-len(s1) / 4] return is_substring(s1, s2 + s2) if __name__ == "__main__": questions = [("erbottlewat", "waterbottle"), ("abc", "bcd")] answers = [True, False] for i, q in enumerate...
#!/usr/bin/env python """ Numbers are represented by a linked list. Implement sum. """ import sys sys.path.append("../") from llist import * def get_data_safe(node): if node == None: return 0 return node.data def sum_llst(head1, head2): ret = None n1 = head1 n2 = head2 carry = 0 ...
''' A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and i...
''' It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2*1**2 15 = 7 + 2*2**2 21 = 3 + 2*3**2 25 = 7 + 2*3**2 27 = 19 + 2*2**2 33 = 31 + 2*1**2 It turns out that the conjecture was false. What is the smallest odd composi...
''' The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? ''' from intlib import prime_set ...
''' How many different ways can one hundred be written as a sum of at least two positive integers? ''' def main(): MAX = 100 pre_table = [1] * (MAX + 1) for k in range(2, MAX): table = [0] * (MAX + 1) for n in range(MAX + 1): table[n] = sum(pre_table[n - i * k] ...
''' The cube, 41063625 (345**3), can be permuted to produce two other cubes: 56623104 (384**3) and 66430125 (405**3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. Find the smallest cube for which exactly five permutations of its digits are cube. '...
''' The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, ...
''' Problem 39 ---------------------- If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120. {20,48,52}, {24,45,51}, {30,40,50} For which value of p <= 1000, is the number of solutions maximised? ''' def count_sols(p): ans ...
## Welcome to Beefy's Brackish Burgers! ## ## Complete with Andrew's idiotproof+++ ## ## Error Prevention Code solutions!(tm) ## ## Andrew Inc: Making overcomplicated ## ## Solutions to simple problems since ## ## 2017 ## #----------------------------------------# import os def cle...
a = float (input("NUM 1 \n")) b = float (input("NUM 2 \n")) w = float (input("NUM 3 \n")) c = input("RAW \n") r = 0 if c=="+": r=a+b+w elif c=="-": r=a-b-w elif c=="*": r=a*b*w elif c=="/": r=a/b/w print (r)
# -*-coding: utf-8 -*- # Create by Jiang Tao on 2016/9/20 # 在Python中,这种一边循环一边计算的机制,称为生成器:generator g = (x * x for x in range(10)) print(g) # 访问生成器的元素 for n in g: print(n, end=" ") print() # 函数中含有yield关键字,那么这个函数就是一个生成器generator def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = ...
print("Enter the temperature(celsius) and wind speed (km/h) and I will calculate the windchill factor") temp_cel = float(input("What is the temperature in celcius?: ")) wind_kmh = float(input("What is the wind speed in km/h?: ")) wc = (13.12 + (0.6215 * temp_cel) - (11.37 * (wind_kmh ** 0.16)) + (0.3965 * temp_cel * (w...
#! /usr/bin/env python3.3 """A simple profiling timer class for timing sections of code. To use: with Timer('A'): do work with Timer('B'): do work with Timer('C'): do work with Timer('B'): do work At exit, a debug log entry will be produced: A : 0.2000 seconds s...
import unittest from numerosRomanos import NumerosRomanos class testNumeroRomano(unittest.TestCase): def setUp(self): self.numero_romano = NumerosRomanos() def testdecimal_I(self): self.assertEqual('I', self.numero_romano.decimal_romano(1), 'I falhou') self.ass...
""" The Lazy Startup Office https://www.codewars.com/kata/578fdcfc75ffd1112c0001a1 Solved 01-24-2017 Description: 7 kyu The Lazy Startup Office A startup office has an ongoing problem with its bin. Due to low budgets, they don't hire cleaners. As a result, the staff are left to voluntarily empty the bin. It has emer...
""" Is the string uppercase? https://www.codewars.com/kata/56cd44e1aa4ac7879200010b Solved 01-24-2017 Description: 8 kyu Task Create a method is_uppercase() to see whether the string is ALL CAPS. For example: is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercas...
from models.abstract_model import AbstractModel import numpy as np import utils.miscellaneous class Random(AbstractModel): """ Represents random model. """ def __init__(self, game): """ Initializes a new instance of Random model for the specified game. :param game: Game that w...
a = int(input("Proporciona un valor:")) valorMinimo = 0 valorMaximo = 5 dentroRango = (valorMinimo <= a <= valorMaximo) # (a >= valorMinimo and a <= valorMaximo) print(dentroRango) if dentroRango: print('dentro de rango') else: print('fuera de rango') vacaciones = False diaDescanso = False if vacaciones or d...
class Rectangulo: def __init__(self, ancho, alto): self.ancho = ancho self.alto = alto def calcularArea(self): return self.ancho * self.alto print('Bienvenid@') ancho = int(input('Introduzca el ancho del rectangulo: ')) alto = int(input('Introduzca el alto del rectangulo: ')) rectang...
""" Description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Category : easy ---------------------...
import math x=int(input("enter the value of x :")) y=int(input("enter the value of y :")) result=math.pow(x,y) print(result)
#!/user/bin/env python3 # -*- coding: utf-8 -*- __author__ = "HymanQin"; ''' 基础 ''' import re,math; # === 输入输出 === # a = input(); # print(a); a = 11; b = "qw"; print(a); print("hello world"); print("hello", "world", "haha"); print("hello %s" % a); print("hello %s" % (a)); print("hello %s %s" % (a, b)); # === 数据类型 =...
import random #生成随机骰子 def getRan(n): list_a = [] for x in range(n): list_a.append(random.randint(1,6)) return list_a userA = getRan(5) userB = getRan(5) print('玩家A骰子为:', userA) print('玩家B骰子为:', userB) #计算骰子总个数 def resultFuc(usera, userb): a = usera + userb b = set(a) result = [] f...
li = [1,2,3,4,5] x = 0 for i in li: x = x + i print(x) print(x)
#生成器的使用 #传统生成器 class New_Iter(object): def __init__(self): self.data = [2, 4, 8] self.step = 0 def __iter__(self): return self def __next__(self): if self.step >= len(self.data): raise StopIteration data = self.data[self.step] print (f"I'm in ...
import os, tempfile class File: """File operator""" def __init__(self, file_path): self.file_path = file_path def __str__(self): return self.file_path def _read(self): with open(self.file_path, "r") as f: return f.read() def write(self, obj): with open (self.file_path, "w") as f: return f.write(...
"""A Probability Calculator.""" import copy import random class Hat: """ A Hat object contains a number of balls of different colors. Parameters ---------- **kwargs The keyword arguments are used for specifying the number of balls of each color that are in the hat object """...
# printing permutations of string def permutations(string,i,j): if i==j: print string return for k in range(i,j+1): m = string[i] string[i] = string[k] string[k] = m permutations(string,i+1,j) m = string[i] string[i] = string[k] string[k] = m string = "abc" permutations(list(string...
s1 = set("Hello") print(s1) set1 = set([1, 2, 3, 4, 5, 6]) set2 = set([4, 5, 6, 7, 8, 9]) print(set1 & set2) print(set1 | set2) print(set1 - set2) # 값 한 개 추가 set1.add(7) print(set1) # 여러 값 추가 set1.update([8,9,10]) print(set1) # 값 제거 set1.remove(5) print(set1)
# guessing number s=9 j=0 while j<3: g=int(input("guess the number = ")) if g==s: print("You guessed it correctly") break else: j+=1 if j == 3: print("you are wrong") ##### use while and else funtion j =0 while j<3: g=int(input("Guess the number = ")) j+=1...
# zeros - The zeros tool returns a new array with a given shape and type filled with 's. # print numpy.zeros((1,2), dtype = numpy.int) #Type changes to int # Ones - The ones tool returns a new array with a given shape and type filled with 's. # print numpy.ones((1,2), dtype = numpy.int) #Type changes to int i...
ab = "hello Word" print(ab.find("o")) print(ab.upper()) print(ab.lower()) print(ab.replace("o", "0")) print("hello" in ab) print(len(ab)) print(ab.title()) x=10 print(10 / 3) # float output print(10 // 3) # Int output print(10 ** 3) #power function print(10 % 3) #modulus x += 3 print(x )
dic={ "name":"Amit Up", "name":"Vibha", # This one replace the value of name "Name":"Eva", "age":31, "email":"gmail" } print(dic, dic.get("surname", "Upadhyay")) # this will return Upadhyay, if key is not found. dic["name"]="Amit" dic["Mobile"]=70426 print(dic, dic.get("Mobile","new num"...
# Dictionary Question ab={"amit@gmail.com" : "amit", "vibha@gmail.com":"vibha","eva@gmail.com":"eva", "amit@yahho.com":"amit" } print(ab) # Create two empty list email=[] name=[] # appended the both the list using items of the ab ditionary for n, m in ab.items(): email.append(n) name.append(m) i=len(a...
cd=[] i=0 while i<5: cd.append(int(input("Enter 5 random number tpo find the sorted list, num = "))) i+=1 print(cd) j=0 i=4 k=0 while j!=5: k=0 while k!=i: if cd[k] > cd[k+1]: temp=cd[k+1] cd[k+1]=cd[k] cd[k]=temp k = k+1 ...
# The from..import statement ''' If you want to directly import the argv variable into your program (to avoid typing the sys. everytime for it), then you can use the from sys import argv statement. ''' from math import sqrt print("The sqaure root of 16 is - ", int(sqrt(16))) '''WARNING: In general, avoid usi...
for i in range(3): for j in range(3): print(f"Co-ordinates are ({i},{j})") ab=[5,2,4,2,2] for i in ab: cd="" for c in range(i): cd+="X" print(cd) print("\n") ab=[2,2,2,2,5] for i in ab: cd="" for j in range(i): cd+="X" print(cd)
# Polynomials is combination of terms with "+" or "-" and terms are (number * variable) - example x2-2xb+b2 - number == coefficient of term # nv = Monomials, nv +(-) nv = binomials, nv +(-) nv +(-) nv = Trinomials, rest are Polynomails. all can be called polynomials import numpy polyarray = numpy.array([float(...
class IceCreamMachine: def __init__(self, ingredients, toppings): self.ingredients = ingredients self.toppings = toppings def scoops(self): ab=[] cd={} for i in self.ingredients: ab.append(i) for i in ab: cd[ab[0]]...
a,b="Mr", "Amit" c=("i", "am", "Eva","Vibha") d,a=c[0:2] e,f=c[-2:] print("A",a ) print("B", b) print("C", c ) print("D",d ) print("A", a ) print("E", e ) print("F", f) print(" I am %d year old and my name is %s" % (30,"Amit")) for a in "Amit": print("Char ", a) else: print("all done")
# Python has a nifty feature called documentation strings, usually referred to by its shorter # name docstrings. DocStrings are an important tool that you should make use of since it # helps to document the program better and makes it easier to understand. Amazingly, we can # even get the docstring back from, say a ...
#if you break out of a for or while loop, any corresponding loop, else block is not executed. while True: s=input("Type your name = ") if s=="Eva": print("She is my lovely daughter") break print("Length of your name is ", len(s)) print("Break is over") #break and continue statement...
import time import random # simplifiyng function # prints text with a timer whenever there is t2t in the text def printpause(text): i = 0 sub_start = 0 while i <= len(text): temporary = text[i:i+3] # print(temporary) if temporary == "t2t": print(text[sub_...
__author__ = 'cheetah' import pandas as pd from pandas import ExcelWriter # Approach for the Problem ''' 1. The person can leaps max up to the Leap Size only i..e cap = 4 , person can make leaps of 1,2,3,4 2. Assuming if the peg size is more than Leap size , then he will do the next leap depending on the remaining...
# # @lc app=leetcode.cn id=94 lang=python # # [94] 二叉树的中序遍历 # # @lc code=start # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def inorderTraversal(self, root): ...
# # @lc app=leetcode.cn id=127 lang=python # # [127] 单词接龙 # # @lc code=start from collections import defaultdict import string class Solution(object): def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] ...