text stringlengths 37 1.41M |
|---|
i = 10
while i>0 :
print('*' * i)
i=i-1
print('Down') |
name = input('Please set up your name: ')
namelen=len(name)
if namelen < 3:
print('name mast be at least 3 characters')
elif namelen >50:
print('name mast be a maxmum of 50 characters')
else :
print("It's a good name!") |
#print("Hello World")
#print(5+5)
'''Rules for creating variables'''
# 1. Variable should start with a letter or an underscore
# 2. Variable cannot start with a number
# 3. It can only contain alpha numeric characters
# 4. Variable names are case sensitive (e.g Yousuf and yousuf are two difference variables)
... |
arr = [1,2,3,4,5,6,7,9,10]
def first_non_consecutive(arr):
if not arr: return 0
for i, value in enumerate(arr[:-1]):
print value
if value + 1 != arr[i + 1]:
return arr[i + 1]
print first_non_consecutive(arr)
# arrayList = ['Apples','Banna','Orange']
# def testing(list):
# fo... |
class doubleEndedQueue:
def __init__(self):
self.limit = 6
self.front = None
self.rear = None
self.db_queue = []
def enq_front(self,ele):
if(self.front == 0):
print("Cannot insert at front")
else:
if(self.front == None and self.rear == None... |
# Write a function that take in an array of integers, and an integer representing a target sum.
# The function should return all the triplets that sum up to the target sum
def three_number_sum(array, targetSum):
array.sort()
triplets = []
for i in range(len(array) - 2):
left = i + 1
right = len(array) - 1
w... |
class LinkedList:
def __init__(self, head=None):
self.head = head
def prepend(self, value):
# head # head
# \ # \
# \ # \
# [23]->[12]->null # [4]->[23]->[12]->null
self.head = Node(value=value, next=self.head)
def append(self, value):
# head # head
# \ # \
... |
# An XOR linked list is a more memory efficient doubly linked list.
# Instead of each node holding next and prev fields,
# it holds a field named both, which is an XOR of the next node and the previous node.
# Implement an XOR linked list;
# it has an add(element) which adds the element to the end,
# and a get(ind... |
# given a list of positive integers, what is the largest sum of non-adjacent items?
# 1 - inefficient recursive solution (maybe 2^n time)
def maxSubsetSumNoAdjacent(lst, idx=0):
# for every number I can either take it, OR the next one. I want to use DP to find the max up to that point.
if idx >= len(lst):
return... |
def find_longest_word(lword:list):
length_value = []
for i in lword:
length_value.append(len(i))
length_value.sort()
for i in lword:
if max(length_value)==len(i):
return i
return "There are two or more elements with equal amount of characters"
print... |
def make_forming(verb:str):
special = ["be","see","flee","knee"]
consonant = "bcdfghjklmnpqrstvwxyz"
vowel = "aiueo"
if verb[-2:] == "ie":
verb = verb[:-2] + "ying"
return verb
if verb[-1] == "e" and verb not in special:
verb = verb[:-1] + "ing"
return verb
if con... |
import os
from InputCreation.TestImage import TestImage
class TestImagePair:
''' TestImagePair holds two TestImage objects-- TestImage member 'BEFORE' as \
the logical first TestImage, and TestImage member 'AFTER' as the logical \
second TestImage
`This class operates at the Test I... |
for i in range(1, 13):
print("{0:2} -> {1:^3} -> {2:4}".format(i, i ** 2, i ** 3))
print()
print("-" * 50)
print()
pi = 22 / 7
print("pi is {0}".format(pi))
print("pi is {0:<12f}|".format(pi))
print("pi is {0:<12.50f}|".format(pi))
print("pi is {0:<12.2f}|".format(pi))
print("pi is {0:52.50f}|".format(pi))
print(... |
import os
# Função que verifica todas as possibilidades de vencedor e retorna se venceu ou não
def verificaCampeao(tabuleiro, simbolo):
if tabuleiro[0] == simbolo and tabuleiro[1] == simbolo and tabuleiro[2] == simbolo:
return simbolo
elif tabuleiro[3] == simbolo and tabuleiro[4] == simbolo and tabulei... |
myVar = input("What is your answer to my 1st question? (yes/no) ")
if myVar == "yes":
myNextVar = input("What is your answer to my 2nd question? (yes/no) ")
if myNextVar == "yes":
[another 1st "then" clause]
elif myNextVar == "no":
[another 2nd "then" clause]
else:
print("Answer my question! You did... |
class Player:
def __init__(self, name, startingRoom, startingItems=[]):
self.name = name
self.currentRoom = startingRoom
self.items = startingItems
def travel(self, direction):
nextRoom = self.currentRoom.getRoomInDirection(direction)
if nextRoom is not None:
... |
#List-6
#Dylan and Avi
#12/13/17
def main():
print "You will be asked for a string and the number of non-space characters will be displayed."
string = raw_input("Enter a string: ")
count = len(string)
countSpace = 0
for i in string:
if i == " ":
countSpace += 1
countNon = co... |
"""
https://adventofcode.com/2018/day/2
"""
from collections import Counter
from itertools import product
from pathlib import Path
def solve_a(codes):
pairs = triplets = 0
for code in codes:
occurrences = Counter(code).values()
pairs += any(count == 2 for count in occurrences)
triplet... |
from __future__ import annotations
import sys
from typing import Iterable, Iterator
class Reader:
"""This class provides methods for reading strings, numbers and
boolean from file inputs and standard input.
"""
def __init__(self, stream: Iterable[str]):
self._stream = stream
@classmethod... |
# #!/usr/bin/env python3
# Created by Malcolm Tompkins
# Created on August 11, 2021
# Last edited on August 22, 2021
# Runs the tic-tac-toe game
import os
import sys
import random
def screen_clear():
# for mac and linux(here, os.name is 'posix')
if os.name == 'posix':
_ = os.system('clear')
else:
... |
# Realice una FUNCIÓN en Python que calcule el índice de masa corporal de una persona y diga el estado en que se encuentre. Debe recibir los parámetros necesarios.
weightKg = int(input("Enter your weight in Kg (example 76): "))
heightM = float(input("Enter your height in meters (example 1.80):"))
def calculateIMC(we... |
class FiguraGeometrica:
def __init__(self, ancho, alto):
self.__ancho = ancho
self.__alto = alto
def area(self):
return self.__alto * self.__ancho
#def get_ancho(self):
# return self.__ancho
#def set_ancho(self, ancho):
# self.__ancho = ancho
#def g... |
class BinaryTree:
def __repr__(self):
return "Binary Tree, Key is " + self.key
def __init__(self, root):
self.key = root
self.left_child = None
self.right_child = None
def insert_left(self, new_node):
if self.left_child == None:
self.left_chil... |
import sqlite3,hashlib,getpass
from password_strength import PasswordPolicy
def userCheck(username):
result= cur.execute("SELECT EXISTS(SELECT 1 FROM users WHERE username=?)",(username,)).fetchone()[0]
return result
def passwordPolicyCheck(password):
policy = PasswordPolicy.from_names(
length=8, ... |
import time
import os
def selection():
os.system('clear')
print("Selection Sort")
print("Masukkan array angka")
print('(pisahkan dengan koma)')
inp = input()
A = inp.split(',')
print("Array Awal : %s" % A)
start = time.time()
for i in range(len(A)):
min_idx = i
for j... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
An example of a Markov model that uses
a dictionary instead of a matrix, which
makes it more readable and easier to specify
"""
import numpy as np
def pick_random_element(prob):
"""
Parameters
----------
prob: {string: double}
A dictionary of ... |
def square(nums):
results=[]
for num in nums:
yield(num ** 2)
mynums = (x**2 for x in [5,4,3,2,8])
print(mynums)
for num in mynums:
print(num) |
import math
def isPower(N):
sqrt = math.floor(math.sqrt(N))
for p in range(2,33):
for A in range(2, sqrt+1 ):
if A**p == N:
print(A,"**",p)
return True
return False
print(isPower(625)) |
# Python 2.7.13
#
# Author: Ryan Vinyard
#
# Purpose: The Tech Academy - Python Course, concept drill
# I've tried to model this script off of the nice/mean drill, to build good habits.
def start(name="", number=0, decimal=0, array=[]):
#This start function allows us to smoothly go from function to function as w... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 28 14:35:20 2021
@author: pablo
Problem
Given two strings s and t, t is a substring of s if t is contained as a contiguous
collection of symbols in s (as a result, t must be no longer than s).
The position of a symbol in a string is the total number of symbols ... |
item = ''
itens = []
maior_item = ''
maior = ''
while item != '0 0 0':
item = input()
itens.append(item)
for x in itens:
compra = x.split(' ')
total = int(compra[1])*float(compra[2])
if maior_item == '':
maior_item = x + ' ' + str(total)
else:
maior = maior_item.... |
q = 0
n = str(input())
m = str(input())
a = list(n)
for i in a:
if i == m:
q += 1
if q == 0:
print('Caractere nao encontrado.')
else:
print('O caractere buscado ocorre {} vezes na sequencia.'.format(q))
|
def Credito(Valor):
Valor = Valor * 2
return Valor
def Debito(Valor):
Valor = Valor / 10
return Valor
ValorFinanceiro = 10
print(Credito(ValorFinanceiro))
print(Debito(ValorFinanceiro)) |
def encontrarMultiplus(n,m):
i = 0
multiplus = []
while i <= n:
if i % m == 0:
multiplus.append(i)
i = i + 1
else:
i = i + 1
return multiplus
numero1 = int(input())
numero2 = int(input())
multiplus = encontrarMultiplus(numero1,numero2)
... |
salario = float(input())
desconto = 0
if salario<=1751.81:
desconto=0.08*salario
print('Desconto do INSS: R$ {:.2f}'.format(desconto))
elif salario>1751.81 and salario<=2919.72:
desconto=0.09*salario
print('Desconto do INSS: R$ {:.2f}'.format(desconto))
elif salario>2919.72 and salario<=5839.45:... |
def somaDigitos():
x = int(input())
soma = 0
while (x != 0):
resto = x % 10
x = (x - resto)//10
soma = soma + resto
print(soma)
somaDigitos()
|
num = float(input())
num = num*100
while num <= 70 or num >= 620 or num%10!=0:
print('Preco invalido, refaca a leitura do pacote.')
num = float(input())
num = num*100
|
# Candidate.py
# Ben Hazlett
# 1/22/2018
# Description:
# Written for the Asymmetric programming challenge. This file
# contains a class written to hold a word called a candidate
class Candidate():
# Constructor: inititalizes dictionaries to empty
def __init__(self, word, confidence):
self.word =... |
from flask import Flask
app = Flask(__name__) # Flask --> class --> object --> app
# __name__ ??
# make object of PWD so that later it will read everything from current working directory
@app.route("/") # route --> decorator --> takes path as an argument
# / --> domain , / --> localhost(127.0.0.1)
def index():
... |
#!/usr/bin/env python3
user_input = input("Please enter an IPv4 IP address:")
print("You told me the PIv4 address is:" + user_input)
|
"""
Points:
- Stones can be attached to existing rows, stones can be moved if all rows stay valid
Valid rows:
- Jokers can be used everywhere; they count for the same number as they represent
- If no valid row can be made; the user picks up a stone from the pot.
Play ends if:
- One of the players placed all his stone... |
socks = "socks"
jeans = "jeans"
laptop = "laptop"
toiletries="toiletries"
luggage = []
item1 = raw_input("what you like to pack?")
luggage.append(item1)
item2 = raw_input("next item to pack?")
luggage.append(item2)
for items in luggage:
print(items.upper())
grades = [
96.0,
100.0,
75.5,
89.5
]
sum = 0
for gr... |
import pylab
from random import shuffle
def bubblesort_anim(a):
x = range(len(a))
imgidx = 0
# bubble sort algorithm
swapped = True
while swapped: # until there's no swapping
swapped = False
for i in range(len(a)-1):
if a[i] > a[i+1]:
a[i+1], a[i] = a[i], a[i+1] # swap
swapped = True
pylab.plot(x... |
PURPLE = '\033[95m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
GREY = '\033[90m'
RESET = '\033[1m'
print(RESET)
grade = float(raw_input("Enter the grade you got on a quiz"))
#todo fill in - and +'s
if(grade >= 90.0):
print(BLUE+"you got an A")
if(grade >= 80.0 and grade < 90.0):
print(... |
n=int(input(':'))
list1=list(map(int,str(n)))
list2=sorted(list(map(int,str(n))))
if list1==list2:
print('DA')
else:
print('NU') |
#simple GUI registration form.
#importing tkinter module for GUI application
from tkinter import *
#Creating object 'root' of Tk()
root = Tk()
#Providing Geometry to the form
root.geometry("800x700")
#Providing title to the form
root.title('Registration form')
#this creates 'Label' widget for Registra... |
import random
number=random.randint(1,9)
chances=0
print("Guess a number ")
while chances<5:
guess=int(input("Enter your guess "))
if guess==number:
print("Congratulations")
break
elif guess<number:
print("too low ")
else:
print("too high ")
chances=chances+1
if not chances<5:
... |
#import panad
import pandas as pd
import numpy as np
#Read data
other_path = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/auto.csv"
df = pd.read_csv(other_path, header=None)
# show the first 5 rows using dataframe.head() method... |
import maxflow
# Create a graph with integer capacities.
g = maxflow.Graph[int](2, 2)
# Add two (non-terminal) nodes. Get the index to the first one.
n0 = g.add_nodes(2)
# Create two edges (forwards and backwards) with the given capacities.
# The indices of the nodes are always consecutive.
g.add_edge(n0, n0 + 1, 1, 2... |
"""
Imagine you have a call center with three levels of employees: fresher, technical lead
(TL), product manager (PM). There can be multiple employees, but only one TL or PM.
An incoming telephone call must be allocated to a fresher who is free. If a fresher
can’t handle the call, he or she must escalate the call to te... |
"""
Implement an algorithm to print all valid (e.g., properly opened and closed) combi-
nations of n-pairs of parentheses.
EXAMPLE:
input: 3 (e.g., 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((()))
"""
import unittest
def parens(n):
parens_of_length = [[""]]
if n == 0:
return parens_of_le... |
"""
Problem: Given 10 identical bottles of identical pills (each bottle contain hundred of pills).
Out of 10 bottles 9 have 1 gram of pills but 1 bottle has pills of weight of 1.1 gram.
Given a measurement scale, how would you find the heavy bottle? You can use the scale only once.
"""
import unittest
def pill_bottl... |
#1: write different list
listofnumber=[1,2,4,5,6,7,8,8,9,7]
print(listofnumber)
listofname=["bishal","bubun","banti","chuni"]
print(listofname)
listofboth=[1,3,"name","book"]
print(listofboth)
#2:accesing element from tuple
tupleof_number=(1,2,3,4)
print(tupleof_number)
#access element
print(tupleof_... |
# Special is a Prey similar to Special and floater
# except it moves faster and has a larger radius.
# It starts off as an orange circle but changes
# to a random color every 15 cycles.
from prey import Prey
import random
class Special(Prey):
radius = 10
max_count = 15
def __init__(self,... |
class Stack:
def __init__(self):
self._data = []
def push(self, x):
self._data.append(x)
def pop(self):
x = self._data[-1]
self._data = self._data[:-1]
return x
def isEmpty(self, ):
return len(self._data) == 0
def clear(self):
self._data = []
... |
"""
File: Project2
Author: Cole Crase
This will allow the user to naviagte the liens of text in a file.
"""
fileName = input("Enter the file name: ")
f = open(fileName, 'r')
Counter = 0
for n in f:
if n:
Counter += 1
print("The number of lines in this file is", Counter)
while True:
num... |
# Hesap Makinesi
print("Toplama = 1 \n"
"Çıkarma = 2 \n"
"Çarpma = 3 \n"
"Bölme = 4")
islem = input("İşlemi Seçiniz: ")
sayi1 = int(input("Sayi 1: "))
sayi2 = int(input("Sayi 2: "))
if islem == "1":
sonuc = int(sayi1) + int(sayi2)
print("Sonuç: ", str(sonuc))
elif islem == "2":
sonuc ... |
# Ekrana çift sayı yazdır
sayi = int(input("Çift sayılar için üst sınır giriniz: "))
for i in range(0, sayi, 2):
print(i)
|
'''
同余定理和次方求模
'''
import math
def congruence(*args, **kwargs):
a = args[0]
b = args[1]
m = args[2]
return m % (a-b) == 0
def powmod(*args, **kwargs):
'''
a^v mod c
'''
a = args[0]
b = args[1]
c = args[2]
if b == 0:
return 1
if b == 1:
return a % c
... |
#EXEMPLO DE CLASSE QUE PRECISA DOS ATRIBUTOS/MÉTODOS DE OUTRA CLASSE PARA FUNCIONAR
class Cart:
def __init__(self):
#LISTA ONDE SERÃO INSERIDOS OS DADOS DE OUTRA CLASSE
self.produtos = []
#RESPONSÁVEL POR INSERIR PRODUTOS NA LISTA
def inserir_produto(self, produto):
self.produtos.app... |
from random import randint
print('Jogo do Par ou Ímpar')
print('-='*11)
c = 0
while True:
jogador = int(input('Digite um valor: '))
computador = randint(0, 11)
soma = jogador + computador
tipo =' '
while tipo not in 'PI':
tipo = str(input('Par ou Ímpar? [P/I] ')).strip().upper()[0]
... |
n=input("Enter the name of item")
q=int(input("Enter the cost of one unit"))
r=int(input("Enter the number of item purchased"))
t=q*r
print("The total expenditure incured by purchasing: ",n,"is",t)
|
## @package File_Decryption_Example
# This project is an example of file decryption using Python. In this
# example, Advanced Encryption Standard (AES) from the Crypto library.
# AES uses a 16, 24, or 32-byte key to decrypt information. In this case, the user must provide
# the key and input file name including loc... |
import numpy as np
from math import asin, pi
# Classe para representar um ponto/vetor, facilitar codigo para as funcoes de operacoes geometricas
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return str(self.x) + " " + str(self.y)
# Soma de doi... |
def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
result = 1
while exp > 0:
result = result * base
exp -= 1
return result
print iterPower(2, 3)
def recurPower(base, exp):
'''
base: int or float.
exp: int >... |
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
from collections import Counter
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return None
root =... |
import unittest
"""
https://www.youtube.com/watch?v=qli-JCrSwuk
"""
def num_ways(s):
if len(s) == 0:
return 0
elif s[0] == '0':
return 0
elif len(s) == 1:
return 1
nw = num_ways(s[1:])
print(f'nw1={nw} + {s[1]} + {s[1:3]}')
if int(s[1:3]) >9 and int(s[1:3])<27:
... |
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head:
return True
if not head.next:
return True
... |
from typing import List
#Print matrix
def printm(M):
for e in M:
print(e)
#Linked Lists:
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def buildList(a):
tail = None
for e in reversed(a):
if tail == None:
... |
from typing import List
"""
From: https://www.youtube.com/watch?v=4UWDyJq8jZg
"""
class Person:
def __init__(self, b,d):
self.b = b
self.d = d
def get_year(persons: List[Person]) -> int:
years = [0 for i in range(2019)]
for p in persons:
years[p.b] +=1
years[p.d] -=1
... |
from typing import List
class NotWorkingRecursiveSolution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
return self.mergeR(intervals)
def mergeR(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals or not intervals[0]:
return []
if len(in... |
from typing import List
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]:
return False
n = len(matrix)
m = len(matrix[0])
l = 0
r = n
mid = l + (r-l)//2
if matrix[n-1][0]<target:
... |
#!/usr/bin/env python
# coding: utf-8
# <p> This is my <b> first Python code </b>.
# $$Hello$$
# $$ c = \sqrt{a^2+b^2} $$
# $$ e^{i\pi} + 1 =0 $$
# $$ e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$$
# $$ f(x) = a_0 + \sum_{n=1}^\infty (a_n cos \frac{n \pi x} L + $$
# $$ ( x + a ) ^n = \sum_{k=0} ^ n (k^n) x^k a^{n-k} $$
... |
#!/usr/bin/env python
# coding: utf-8
# In[17]:
import numpy as np
a = np.arange(15).reshape(3,5)
a
# In[18]:
print(np.array([8,4,6,0,2]))
# In[ ]:
# In[19]:
print('create a 2-D array by passing a list of lists into array().')
A = np.array([[1,2,3],[4,5,6]])
print(A)
print('access elements of the array... |
# ========================
# Information
# ========================
# problem link : https://www.hackerrank.com/challenges/30-data-types/problem
# Language: Python
# ========================
# Solution
# ========================
# Declare second integer, double, and String variables.
ii =int(input())
d... |
#!/usr/bin/env python
# coding: utf-8
# In[8]:
#2
for i in range(1,21):
for j in range(i+1,21):
if (i+j)%2==0:
print("Sum is Even,Pair is: ",i,j,"The sum is: ",i+j)
else:
print("For",i,j,"Nothing can be done")
# In[21]:
#1
x=[1,2,3,4,[10,20,30,40,[100,200,300,400],'ris... |
def knapsack(n, W):
if memo[n][W] != None:
return memo[n][W]
if n == 0 or W == 0:
result = 0
elif w[n] > W:
result = knapsack(n-1, W)
else:
temp1 = v[n] + knapsack(n-1, W-w[n])
temp2 = knapsack(n-1, W)
result = max(temp1, temp2)
memo[n][W] = result
... |
# max frequency with o(1)space and o(n) time
# condition no two max frequecny only one
# for more than one eg (1,1,2,2)
# check next program
# https://www.geeksforgeeks.org/find-the-maximum-repeating-number-in-ok-time/
l = list(map(int,input("Enter Array : ").split(' ')))
#length
k = len(l)
for i in range(k):
l[... |
from turtle import Turtle
from car import Car
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_CAR_SPEED = 5
MOVE_INCREMENT = 3
LANE_POSITIONS = [ (300,-100) , ( 300,0) , (300 , 100 ) , (300, 200 ) ]
class CarManager(Turtle):
def __init__(self):
super().__init__()
... |
# more method with seatch(). search() will return an object
import re
pattern = r"colour"
text = "Blue is my favourite colour"
match = re.search(pattern, text)
if match:
print(match.start())
print(match.end())
print(match.span())
'''
start() - Returns the starting index of the match.
end() - Returns the... |
n = int(input("Enter n = "))
sum =0
i=1
while i<=n :
sum = sum + i
i = i + 1
print(sum) |
file_open=open("Student.txt","r")
text=file_open.readlines()
# by using readlines(), we can make a list of Student.txt file's item.
print(text)
file_open.close()
file=open("Student.txt","r")
for line in file:
print(line)
file.close()
|
'''
Types of Inheritance:
i) Hierarchical Inheritance
ii) Multi-Level Inheritance
iii) Multiple Inheritance
'''
class A():
def display1(self):
print("I am inside A class")
class B(A):
#display1()
def display2(self):
print("I am inside B class")
class C(B):
#display1()
#display... |
class Shape:
def __init__(self,Var1,Var2):
self.Var1=Var1
self.Var2=Var2
def area(self):
print("I am area method of Shape class")
class Traingle(Shape):
def area(self):
area=0.5*self.Var1*self.Var2
print("Area of Traingle=",area)
class Rectangle(Shape):
def... |
books=[]
books.append("Learn C") # append() is used to push value into the stack
books.append("Learn C++")
books.append("Learn Java")
print(books)
books.pop()
print(books)
print("The top most book is : ",books[-1])
# -1 index always show the last item
books.pop()
print(books)
print("The top most book is : ",books[-... |
'''
Two types of functions:
i) Library function
ii) User Defined Function
'''
def add(x,y):
sum=x+y
print("Summation is =",sum)
add(10,20)
add(78,89) |
try:
num1 = int(input("Enter 1st number ="))
num2 = int(input("Enter 2nd number ="))
result = num1 / num2
print(result)
except (ValueError,ZeroDivisionError):
print("You have to enter correct input")
finally:
print("Thanks")
|
name=input("Enter Your Name:") # by input(), we can take input from user.
age=input("Enter Your Age:") # by input(), we can only take string data type.
cgpa=input("Enter Your CGPA:")
print("Personal Information:")
print("========================")
print("Name= "+name)
print("Age= "+age)
print("Cgpa= "+cgpa) |
import itertools
def codebook(n):
pool = '0', '1'
o = open('binarylength' + str(n) + '.txt', 'w')
for item in itertools.product(pool, repeat=n):
o.write(str(item) + "\n")
return item
codebook(5)
def weight(n, s):
empty = []
for i in range(s):
empty.append(0)
for i in range... |
class Circle ():
'''
Calculates the circumference of a circle
Input radius
'''
pi = 3.14
def __init__(self,rad=1):
self.rad = rad
def calculate(self):
return self.rad * self.pi * 2
|
# File halve.py
# Enter a value and cut it half
#print ( "Enter a value : ", end='')
value = int(input("Enter a value : "))
print(value/2)
#print("Half of the " , value , " is " , int(value)/2) |
def triplet(text):
'''
PAPER DOLL: Given a string, return a string where for every character in
the original there are three characters
'Hello' -> HHHeeellllllooo
'''
res = ''
for c in text:
res += c*3
return res |
print ( " Enter the first Number " , end='')
num1 = int ( input() )
print ( "Enter the second number ", end='\n')
num2 = int ( input() )
print ( "\n Sum of two number is = " , num1+num2 , "\n Substraction of two number is = ", num1-num2 , "\n Multiplication of two number is = ", num1*num2 )
print (' --------------... |
def gen(n):
""" Generates the first n perfect squares, starting with zero:
0, 1, 4, 9, 16,..., (n - 1)2. """
for i in range(n):
yield i**2
for p in zip([10,20,30,40], gen(int(input('Enter the positive number in (0 to 10)')))):
print(p, end = ' ')
for p in zip([1,2,3,4,5,6],[... |
#Drawing polygon
import turtle
import random
# Draws a regular polygon with the given number of sides.
# The length of each side is length.
# The pen begins at point(x, y).
# The color of the polygon is color.
def polygon(sides, length, x, y, color):
turtle.penup()
turtle.setposition(x,y)
turtle.pendown(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from .Vector import Vector
class Matrix(object):
""" 矩阵 """
def __init__(self, lst2d):
""" lst2d 是个二维数组"""
self._value = [row[:] for row in lst2d]
def __str__(self):
return "Matrix({})".format(self._value)
__repr__ = __str__
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 21:30:12 2019
@author: Tony Yang
@email: t2yang@eng.ucsd.edu
@github: erza0211064@gmail.com
Description:
Class Lidar_range deal with range filter, which crops all lidar data between given minimum and maximum.
There will be only one scan in each object.
Library used... |
# No keyword replacement for abstract but it tells that interp. dah
# its gonna be implement in subclass and not here. daeway it works.
# thing to notice for polymorphism is that the employee
# creating an abstract base class
class Employee:
def determine_weekly_salary(self, weeklyHours, wage):
raise N... |
# Write a Python program to replace last value of tuples in a list. Go to the editor
# Sample list: [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
# Expected Output: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]
t1 = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
for i in range(len(t1[0])):
t1[i] = t1[i] + (100,)
p... |
# . Write a Python program to convert a given tuple of positive integers into an integer.
# Original tuple:
# (1, 2, 3)
# Convert the said tuple of positive integers into an integer:
# 123
t1 = (1, 2, 3)
s1 = ''
for i in t1:
s1 += str(i)
print(int(s1))
# another way
t1 = (1, 2, 3, 5, 5, 6)
t2 = str(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.