text stringlengths 37 1.41M |
|---|
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
self.hash = {}
newHash = hash(longUrl)
short = 'https://tinyurl.com/' + str(newHash)
self.hash[short] = longUrl
return... |
from tree_learning import *
import random
class Simple_Example(object):
def __init__(self,label,weight=1.0):
self.label = label
self.weight = weight
self.features = dict()
class Simple_Feature(object):
def __init__(self,name):
self.feature_name = name
def query(self,simple_example):
return simple_ex... |
def heading(word, level=1):
if level <= 1:
return f'# {word}'
if level == 2:
return f'## {word}'
if level == 3:
return f'### {word}'
if level == 4:
return f'#### {word}'
if level == 5:
return f'##### {word}'
return f'###### {word}' |
def average_mark(*marks):
sum = 0
count = 0
for mark in marks:
sum += mark
count += 1
avg = sum / count
return f'{avg:.1f}'
|
class Player:
def __init__(self, color, name=""):
"""
Params:
color : int
0 : Red; 1 : Yellow
name : str
Name of the player, if left empty the computer is the player.
"""
self.color = int(color) # yellow or red
self... |
import random
dishes_string = ('eggs, Cake, cake, Spam, Spam ,,, Butter, New, new, cookie, water , juice')
drink_string = ["Water","Juice","Sprite","Coffee"]
new_list =[]
dish_set = []
class MyServing():
'''ALL that you ordered in the restaurant'''
def __init__(self, dish_name):
self.name = d... |
class Array:
def __init__(self, value, N):
self.value = value
self.N = N
def __getitem__(self, index):
return self.value[index]
def __setitem__(self, index, value):
self.value[index] = value
def __eq__(self, other):
if not isinstance(other, Array):
... |
# # https://wikidocs.net/7031
print("121")
char = input("알파벳 : ")
if char.islower():
print(char.upper())
else:
print(char.lower())
print("\n122")
score = int(input("score : "))
if score <= 20 and score >= 0:
grade = "E"
elif score <= 40:
grade = "D"
elif score <= 60:
grade = "C"
elif score <= 80:
... |
from __future__ import print_function
import banyan_c
class MinGapUpdator(object):
"""
Updates nodes by the minimum, maximum, and min-gaps of their subtrees. Allows trees employing this to
efficiently answer what is the smallest gap in their keys.
Example:
>>> t = Sor... |
from matplotlib import pyplot as plt
import numpy as np
x = np.arange(1,10,0.1)
y = x*0.2
y2 = np.sin(x)
#2개의 식이나 시리즈의 값을 동시에 보여주면서 비교
#범례 레전드를 통해 보여준다.
#범례의 위치를 정해준다.
plt.plot(x,y,'b',label='first')
plt.plot(x,y2,'r',label='second')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('matplotlib sample')
plt.lege... |
def findNearestSquareNumber(n):
temp=0
if n**2>temp:
print ('%s' % n**2)
if (n+1)**2>temp:
print (n)
for i in range(10):
print(findNearestSquareNumber(i))
|
str11="Hello Python. Nice to meet you. Fine, thank you"
aa=str11.split(" ")
print(aa)
a="z"
print(ord("z"))#어떤 문자의 아스키 코드 값을 출력
print(chr(122))#어떤 아스키 코드의 문자를 출력
|
#일단 넘파이 라이브러리를 임포트한다.
import numpy as np
import matplotlib.pyplot as plt
#x의 범위는 0에서 10 까지
x=np.arange(-5,5,0.1)
y=np.sin(x)
y2=np.cos(x)
plt.plot(x,y, label='sine')
plt.plot(x,y2, label='cosine')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title('Sin and Cosine Graph')
plt.legend()
plt.show()
|
my_dict={
'go':'가다',
'eat':'먹다',
'run':'달리다',
'sing':'노래하다',
'make':'만들다',
'ask':'물어보다'
}
#print(my_dict)
#print(my_dict['go'])
#print(my_dict['eat'])
#print(my_dict['run'])
for key in my_dict.keys():
print(key)
for items in my_dict.items():
print(items)
for values in my_dict.values()... |
word=input('단어를 입력하세요 : ')
is_palindrom=True
for i in range(len(word)//2):
if word[i] != word[-1-i]:
is_palindrom=False
break
print(is_palindrom) |
# 데이터 분석하기
a=1
b='hello'
# 위와 같이 값 하나를 가진 변수를 '스칼라'라고 부른고
a = [1, 2, 3]
b = ['hello', 'world']
# 위와 같이 여러 값을 가진 변수를 '벡터'라 부른다.
# 데이터 분석은 주로 이런 '벡터를 다룬다.
# DataFrame의 변수도 결국 '벡터'이다.
# 이런 '벡터'를 pandas에선 Series라 부르고
# numpy는 ndarray라 부른다.
# 파이썬에서 제공하는 벡터를 다루는 몇 가지 함수를 알아보자.
all([1, 1, 1]) #벡터 데이터 모두 True면 True 반환
an... |
"""
import pprint
# SOLUTION: https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python
hot_drinks = {
'Dalgona Coffee (Original - Hot)': [2.75, 15],
'Dalgona Coffee (Strawberry - Hot)': [3.00, 7],
'Dalgona Coffee (Chocolate - Hot)': [3.00, 8],
'Dalgona... |
import sets_in_python as AbstractSet
class Set(AbstractSet.AbstractSet):
def __init__(self, elems=()):
AbstractSet.AbstractSet.__init__(self)
self.rep = []
self.insertAll(elems)
def contains(self, a):
return a in self.rep
def insert(self, a):
if a not in self.rep:
self.rep.append(a)
return self... |
évszak = input('Melyik évszak van? (ny/ő) ')
esik = input('Esik? (i/n) ')
szél = input('Fúj a szél? (i/n) ')
if (évszak == 'ny' and szél == 'n') or (évszak == 'ő' and esik == 'n' \
and szél == 'n'):
print('megyünk')
else:
print('maradunk') |
user_number = int(input("Pick a number zero or greater: "))
while user_number < 0:
user_number = int(input("NO NEGATIVES! Pick again: "))
def fibonacci(num):
a = 0
b = 1
if num == 0:
return a
elif num == 1:
return b
else:
for i in range(2, num + 1):
c = a + ... |
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
%matplotlib inline
#reading the dataset crime_data.csv
crime_df=pd.read_csv('crime_data.csv')
print(crime_df.head())
print(crime_df.columns)
#Selecting some of the important features
crime_data=crime_df[['States/... |
'''
https://www.hackerrank.com/challenges/py-introduction-to-sets/problem
'''
def test_set(_str):
print(set([t for c in _str.split(" ") for t in c if t != ' ']))
test_set(input())
def test_set_dict(_dict):
print(set(_dict))
test_set_dict({"a": 97, "b": 98})
# print(set(enumerate(['H', 'a', 'c', 'k', 'e... |
list=[1,2,3,4,5]
print list
input=input('enter the integer: ')
if (input in list):
print "your int value is in the list"
else :
print 'your int value is not in the list'
|
from math import atan2
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, v):
return Vector(self.x - v.x, self.y - v.y)
def __add__(self, v):
return Vector(self.x + v.x, self.y + v.y)
def cross(self, v):
return self.x * v.y - v.x * self.y
def dot(v):
return self.x * ... |
# The purpose of this file is to store the functions that generate standard bars.
# Standard bars are a way of recreating the chronological time bars so as to better reflect the inflow and outflow of (dollars, volume etc) TODO try and make this easier to understand.
# TODO: Implement Bar creation class that is for st... |
a=str(input('Enter your string'))
vow=0
cons=0
wspace=0
digit=0
for i in range(0,len(a)):
if(a[i] in ('a','e','i','o','u')):
vow+=1
elif(a[i]==' '):
wspace+=1
elif(a[i].isdigit()):
digit+=1
else:
cons+=1
print(vow,cons,digit,wspace) |
dictionary = {
'k':'khong',
'any': 'anh yeu',
'eny': 'em yeu',
'vk': 'vo',
'ck': 'chong',
'ik': 'di',
'mk': 'minh',
}
while True:
print("***************")
for i in dictionary:
print(i, end = ' ')
print('\n')
key = input("your code? ")
if key in dictionary.keys():
... |
def distance(str1, str2, m, n):
if m == 0:
return n
if n == 0:
return m
if str1[m-1] == str2[n-1]:
return distance(str1, str2, m-1, n-1)
return 1 + min(distance(str1, str2, m, n-1),
distance(str1, str2, m-1, n),
distance(str1, str2, m-1... |
#
# @lc app=leetcode.cn id=1 lang=python3
#
# [1] 两数之和
#
# https://leetcode-cn.com/problems/two-sum/description/
#
# algorithms
# Easy (44.61%)
# Total Accepted: 248.2K
# Total Submissions: 556.5K
# Testcase Example: '[2,7,11,15]\n9'
#
# 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
#... |
x =[[0,1,2], #Initializing MATRIX-1
[3,4,5],
[6,7,8]]
y =[[-4,-3,-2], #Initializing MATRIX-2
[0, 2, 1 ],
[1, 4, 2 ]]
sum=[[0,0,0], #Iitializing SUM MATRIX
[0,0,0],
[0,0,0]]
for i in range(len(x)): #Iterating through row of the matrix
for j in ra... |
def sumf(n): #Defining function to find sum
if n == 1: #Checking if number of terms is 1
return 0
elif n == 2: #Checking if number of terms is 2
return 1
else:
a,b,sum=0,1,1 #Initializing 1st and 2nd terms and sum variable
for i in range(2... |
#the method two steps:
#first we need sort target
#second we fix one, others are left point and right point respect
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
sortedlist = sorted(nums)
... |
#first,initial primes=[1]*n and primes[0:2]=0
#according to i*i,i*(i+1),i*(i+2).... all numbers are not primes
#then primes[i*i:n:i]=0
#importance
#if primes[j]=0 and i<j,then primes[i*i:n:i] includes primes[j*j:n:j],we don't need to compute
#because i*x=j, j*x'=i*(x*x')
class Solution(object):
def countPrimes(self... |
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('shopping_list_protein.csv')
print(df.head())
print('\n -------------------------------\n ')
# print(df['Protein per 100g'])
df = df[['Name', 'Price', 'Weight/Volume(ml/g)', 'Protein per 100g',
'Carbon Footprint (g)']]
print(df.head())
print... |
"""
Create a function that will take a string as an input and return the 1st non-unique letter of a string.
“Google” => “l”
“Amazon” => “m”
If there are no unique letters, return an empty string: “xoxoxo” => “”.
How would you test it? How would you handle edge cases?
"""
# def return_uniq_letter(n: str):
# for i ... |
# 1
def calculator():
operation = ""
while operation != "0":
operation = input("Please select operation (+, -, *, / and 0 for exit):")
if operation == "+":
a = int(input("Enter the first number:"))
b = int(input("Enter the second number:"))
print(f'{a} + {b} =... |
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key: int) -> int:
if key not in self.cache:
print ("-1")
return -1
else:
self.cache.m... |
turnNum = 0
def inputPlayerLetter():
letter = ''
while not (letter == 'X' or letter == 'O'):
print('Do you want to be X or O?')
letter = input().upper()
if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']
grid = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
def dr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 20 16:53:40 2019
@author: Benedict Wilkins
"""
import numpy as np
import itertools
from inspect import signature
from ..debugutils import assertion
from . import accumulate
from . import function
__all__ = ('accumulate', 'function')
''' #meh re... |
"""
Each ListNode holds a reference to its previous node
as well as its next node in the List.
"""
class ListNode:
def __init__(self, value, prev=None, next=None):
self.prev = prev
self.value = value
self.next = next
class DoublyLinkedList:
""" Our doubly-linked list class. It holds ... |
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class HashTable:
def __init__(self):
# in a fully-featured hash_table will have prime cap and it will be alterable
# but for the sake of simplicity, we'll implement separate c... |
class Heap:
def __init__(self, comparator=lambda x, y: x > y):
self.heap = [0]
self.length = 0
self.comparator = comparator # defaults to MaxHeap
def __len__(self):
return self.length
def insert(self, value):
self.heap.append(value) # add key to heap
self.... |
"""
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree.
This part of the project comprises two days:
1. Implement the methods `insert`, `contains`, `get_max`, and `for... |
import numpy as np
from tkinter import *
import tkinter.messagebox
import queue
import copy
#node class used for building tree
class Node():
def __init__(self, char, number, left=None, right=None, parent = None):
self.char = char # The node character
self.number = number # number of time... |
from com.math.fraction.Fraction import Fraction
class VertexSolver:
def __init__(self, h, k, x, y):
self.h = h
self.k = k
self.x = x
self.y = y
@classmethod
def from_user_input(cls):
h = float(input("h: "))
k = float(input("k: "))
x = float(input("x... |
# Try connecting to the database "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# If the database does not exist, you will get an error.
Creating a Table
# To create a table in MySQL, use the "CREAT... |
import string,random
# print(object(s), sep=separator, end=end, file=file, flush=flush)
# Parameter Description
# object(s) Any object, and as many as you like. Will be converted to string before printed
# sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default is ' '
# end='e... |
"""
Board
"""
from random import random
class Object:
"""
Player
"""
def __init__(self, x, y, width, height, image_url):
self._position = (x, y)
self._size = (width, height)
self._image_url = image_url
@property
def position(self):
return self._position
@p... |
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def target_sum_bst(root, target):
if root == None:
return 0
if target == root.value and root.left == None and root.right == None:
return True
if target_sum_bst(... |
def reverse_integer(num):
sign = num//abs(num)
num = abs(num)
reverse = num % 10
num = num // 10
while num != 0:
reverse = reverse * 10 + num %10
num = num // 10
reverse *= sign
return int(reverse)
#print(reverse_integer(135))
# 531
#print(reverse_integer(-321))
# -123
""... |
from texttable import Texttable
import random
import copy
class Board:
def __init__(self):
self._board = []
for i in range(9):
line = []
for j in range(9):
line.append(-1)
self._board.append(line)
s = "ABCDEFGH"
for i in range(9):
... |
#十进制转十六进制
while True:
try:
n = int(input())
print(hex(n)[2:].upper())
break
except:
break |
import streamlit as st
st.title("IMPROVISED E.M.I CALCULATOR")
p = st.slider("Principle",1000,10000000)
n = st.slider("Tenure(in months)",1,120)
r = st.slider("R.O.I",0.01,15.00)
m = st.slider("Period after which the Outstanding Loan Balance is calculated (in months)",1,60)
n = n*12
r = r/12
m = 1 - (n*12)
... |
# _*_ encoding:utf-8 _*_
"""
# -*- coding: utf-8 -*-
# @Time : 2019/9/4 16:13
# @Author : yangfulong
# @FileName: 快排.py.py
# @Software: PyCharm
# @Blog :https://www.yangfulong.top/
---------------------
版权声明:
原文链接:
"""
quick_sort01 = lambda array: array if len(array) <= 1 else quick_sort01([item for item in ... |
def listCount1():
a = [1, 2, 3, 1, 1, 2]
dictdata = {}
for key in a:
print(key)
dictdata[key] = dictdata.get(key, 0) + 1
return dictdata
def listCount2():
from collections import Counter
a = [1, 2, 3, 1, 1, 2]
return Counter(a)
def listCount3():
import pandas... |
# _*_ encoding:utf-8 _*_
"""
# -*- coding: utf-8 -*-
# @Time : 2019/9/12 10:11
# @Author : yangfulong
# @FileName: 121. 买卖股票的最佳时机.py
# @Software: PyCharm
# @Blog :https://www.yangfulong.top/
# @Github : https://github.com/fulongyang
---------------------
版权声明:
原文链接:
"""
class Solution:
@classmethod
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None: return l2
... |
# 最快的解法:转换为字符串,直接倒序输出
x = -12345
if x < 0:
flag = -1
else:
flag = 1
x_str = str(abs(x))
x_reverse = int(x_str[::-1])
if x_reverse <= 2**31-1:
output = flag * x_reverse
else:
output = 0
print(output) |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None: return l2
... |
# 方法二:一次遍历(beat 99.28%)
# 定义两个point:first和second,距离相差n
# first往前走,second也往前走,这样当first到达尽头的时候,second就是(length-n),直接将second指向的节点删除
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def printlist(self):
now = self
printstr = ''
while now.next != None:
... |
def is_terminal(state):
""" To make algorithm optimal, a way
to record depth is required. TODO.
Return 1 if maximizer (X) wins.
Return (-1) if minimizer (O) wins.
Return 0 if a tie occurs.
is_terminal(state) integrates the
utility function. """
# Horizontal che... |
from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.V= vertices
self.graph = []
def addEdge(self,u,v,w):
self.graph.append([u, v, w])
def printArr(self, dist):
for i in range(self.V):
if i==8:
print("The Sortest Dist... |
from tkinter import *
from PIL import Image , ImageTk
from tkinter import messagebox
import random
import time
class gameHome(Tk):
def __init__(self , master ):
master.attributes('-fullscreen',True)
plrname = StringVar()
def startGame():
if plrname.get():
impor... |
# Ambas funciones son lo mismo
def retrocontador(e):
print("{},".format(e), end="")
if e != 0:
retrocontador(e-1)
print(retrocontador(5))
def contadoratras(e):
print("{},".format(e), end="")
if e == 0:
return None
contadoratras(e-1)
print(contadoratras(10))
def sumatorio(... |
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("TIC-TAC-TOE")
#root.geometry("300x300")
root.configure(background = "light green")
#the main frame
Mainframe = LabelFrame(root)
Mainframe.pack()
#the game frame
gameframe = LabelFrame(Mainframe,padx = 10,pady = 10,bg = "blue")
gameframe.pac... |
def practice_1():
lista = ['mate','fisica','quimica','historia','lengua',]
print(f'yo estudio {lista}')
notas = []
for i in lista:
nota = input('que nota sacaste en cada asignatura?: ')
print(f'en {i} sacaste {nota}')
notas.append(nota)
print(notas)
def pract... |
def practice_1():
nomb = input('cual es tu nombre?: ')
nume = int(input('escribe el numero de reps: '))
print(f' {nomb} tiene {len(nomb)} letras')
math1 = 2+3/2.5**2
print(math1)
def practice_7():
horas = int(input('numero de horas trabajadas?: '))
coste = horas * 1000
pag... |
def run():
curso = input('cual es tu curso favorito en platzi?: ')
veces = int(input('que cantidad de veces se repite?: '))
for i in range(veces):
print(curso)
if __name__ == '__main__':
run() |
import math
def triangulo():
print('escoge la base y la altura: ')
base = int(input('cual es la base?: '))
alt = int(input('cual es la altura?: '))
area=int (base) * int (alt) / 2.0
print('el area es: ' + str(area))
def cuadrado():
print('lado del cuadrado: ')
lado = float(inp... |
def run():
curso = input('cual es tu curso favorito en platzi?: ')
veces = int(input('que cantidad de veces se repite?: '))
if veces > 15:
for i in range(3):
print(curso)
print('tu numero es muy grande')
else:
for i in range(veces):
prin... |
from bs4 import BeautifulSoup
import requests
site = requests.get("https://www.climatempo.com.br/").content
# objeto site está recebendo o conteudo da requisição http do site...
soup = BeautifulSoup(site, 'html.parser')
# objeto soup está baixando do site o html desse site.
print(soup.prettify())
# transforma a estru... |
import math
def solve():
firstLine = list(map(lambda x: int(x) , input().split(' ')))
minimumPrice = math.inf
for i in range(firstLine[2]):
price = input()
beds = list(map(lambda x: int(x) , input().split(' ')))
if (firstLine[0] * int(price)) > firstLine[1] or firstLine[0] > max(beds):
# precio mayor a pre... |
def add(a,b):
sum=a+b
print(sum)
def sub(a=10,b=6):
diff=a-b
print(diff)
def mul(a=8,b=5):
ml=a*b
print(ml)
def div(b=100,a=10):
dv=a/b
print(dv)
a=10
b=20
add(a,b)
sub()
mul(a,b)
div()
|
import math
def is_square(n):
return float(math.sqrt(n)).is_integer()
print(is_square(3)) |
import unittest
def staysStill(dir1, dir2):
if (dir1 == 'NORTH') and (dir2 == 'SOUTH'):
return True
elif (dir1 == 'SOUTH') and (dir2 == 'NORTH'):
return True
elif (dir1 == 'EAST') and (dir2 == 'WEST'):
return True
elif (dir1 == 'WEST') and (dir2 == 'EAST'):
return True
return False
def dirReduc(arr):
i... |
from tkinter import *
from tkinter import filedialog
# PARAMETERS
# graphics
WINDOW_SIZE = 600 # pixels
GRID_LINE_WIDTH = 2 # pixels
SYMBOL_WIDTH = WINDOW_SIZE/12 # pixels - adjust ratio
# 0-1 : size of a symbol relative to it's cell
# bigger than 1 is too much
SYMBOL_SIZE = 0.5
X_COLOR = 'dodger blue'
O_COLOR = 't... |
#Exercicio 8
''' Faça uma funcao que recebe uma lista de strings
e retorna as palavras concatenadas com ' oi ' entre elas.
Exemplo:
concatena(['palavra1', 'palavra2'])
'palavra1 oi palavra2'
'''
def concatena(lista):
return str.join(' oi ', lista) |
#exercicio listas 1
'''
Escreva uma função que recebe uma lista
e retorna o tamanho dela.
'''
def tamanho_lista(lista):
tamanho = 0
for item in lista:
tamanho = tamanho + 1
return tamanho
tamanho = tamanho_lista([5,4,3,2,5,4,3]) |
# numero = int(input("Digite um numero: "))
# while numero < 100:
# print(" " + str(numero))
# numero = numero + 1
# print("Laço encerrado....")
####################################################################################################
#
# resposta = "SIM"
# while resposta == "SIM":
# nivel = inp... |
from collections import namedtuple
if __name__ == '__main__':
iters, cols = int(input()), input().split()
Student = namedtuple('Student', cols)
print(sum([float(Student._make(input().split()).MARKS) for _ in range(iters)]) / iters)
|
from datetime import datetime
if __name__ == '__main__':
dt_format = '%a %d %b %Y %H:%M:%S %z'
for t_itr in range(int(input())):
print(int(abs((datetime.strptime(input(), dt_format) - datetime.strptime(input(), dt_format)).total_seconds())))
|
def wrapper(f):
def fun(l):
# complete the function
for i, phone in enumerate(l):
second = phone[-5:]
first = phone[-10:-5]
l[i] = '+91 ' + first + ' ' + second
f(l)
return fun
@wrapper
def sort_phone(l):
print(*sorted(l), sep='\n')
if __name... |
#!/usr/bin/python3
if __name__ == "__main__":
from collections import namedtuple
# sample named tuple
Book = namedtuple("Book", "author title genre")
books = [
Book("Smith", "Time To Die", "Action")
,Book("Smith", "Viscious Circle", "Action")
,Book("Smith", "Elephant Song", ... |
#!/usr/bin/python3
class Restaurant():
""" A simple class for a dog """
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def open_restaurant(self):
print(self.restaurant_name.title() + " is open!")... |
#!/usr/bin/python3
from collections import defaultdict
num_items = 0
def tuple_counter():
global num_items
num_items += 1
return (num_items, [])
if __name__ == "__main__":
d = defaultdict(tuple_counter)
d['a'][1].append("hello")
d['b'][1].append("world")
d['a'][1].append("goodbye")
print(d)
|
#!/usr/bin/python3
"""
Refer to discussion in formatting_template_example.py before reading about format conversions.
A format rule is applied as {substitute_name:format} over a placeholder.
The format function substitutes the variable name passed to it into the placeholder.
A {substitute_name!conversion} is also av... |
#!/usr/bin/python3
favourite_languages = {
'peter': 'c++',
'liz': 'java',
'vincent': 'pl/sql',
'chris': 'bash',
'seamus': 'C#',
'sean': 'pl/sql',
'allan': 'java'
}
print ("The following languages are listed:")
for language in favourite_languages.values():
print(language.title())
print ("\nThe followin... |
#!/usr/bin/python3
import re
text1 = "Espanol"
text2 = "Espana"
pattern = re.compile("Espan[aol]")
match = pattern.search(text1)
if match:
print(text1, " matched")
# the problem is the following, "Espanl" would also match
text1 = "Espanl"
pattern = re.compile("Espan[aol]")
match = pattern.search(text1)
if match:... |
#!/usr/bin/python3
import unittest
from format_name import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'format_name.py' """
def test_first_last_name(self):
"""Do names like 'Janis Joplin' work? """
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(for... |
#!/usr/bin/python3
"""
Numpy arrays have several attributes and methods that can be used to obtain information and effect change.
Numpy arrays are generally created with np.array.
'zeros', 'ones' & 'empty' are convenient methods
to initialise numpy arrays.
You can also use np.ndarray, but it is not recommended (as per... |
#!/usr/bin/python3
from format_name import get_formatted_name
print("Enter 'q' at any time to quit.")
while True:
first = input("\nEnter first name: ")
if (first == 'q'):
break
last = input("Enter last name: ")
if (last == 'q'):
break
formatted_name = get_formatted_name(first,last)
print("Formatt... |
#!/usr/bin/python3
"""
Pythons look behind mechanism is fundamentally different to the look ahead.
Look behinds are only able to match fixed-width patterns.
Fixed width patterns do not contain variable length matches such as quantifiers.
Alternations are allowed, but only if the alternatives have the same length.
"""
i... |
#!/usr/bin/python3
"""
Read tuple_sort.py before continuing.
Using 0 and -1 as the index into a list, you can obtain the first and last element respectively. Tulpe unpacking can then be used, if the element in a list is a tuple.
A namedtuple can be used to name each attribute within the tuple.
"""
import operator
from ... |
#!/usr/bin/python3
import re
pattern = re.compile(r'^<HTML>')
# [:2] means slice of string from the beginning up to the 3rd character,
"""
for example;
>>> text="Hello World"
>>> text[:3]
'Hel'
>>> text[3:]
'lo World'
>>> text[:-3]
'Hello Wo'
"""
# [2:] means slice of string from the 3rd character up to the end of ... |
#!/usr/bin/python3
import pandas as pd
import numpy as np
pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns', 8)
pd.set_option('display.max_rows', 10)
pd.set_option('display.width', 80)
sp500=pd.read_csv("sp500.csv",index_col="Symbol",usecols=[0,2,3,7])
# columns can be dropped us... |
#!/usr/bin/python3
"""
Numpy arrays can be stacked. They can be stacked in several ways:
Assuming we have the following array:
a = np.arange(9).reshape(3,3)
c = np.copy(a)
Horizontal Stacking
===================
a appears as follows:
[
[0, 1, 2],
[3, 4, 5],
[6, 7, 9]
]
Multiply a by ... |
#!/usr/bin/python3
import pandas as pd
import numpy as np
london_temperatures=pd.Series([19,19])
cape_town_temperatures=pd.Series([13,14])
# create a dataframe from 2 Series's without column names
x=pd.DataFrame([london_temperatures, cape_town_temperatures])
print(x) # lists without column names
# specifying column ... |
#!/usr/bin/python3
import pandas as pd
import numpy as np
sp500=pd.read_csv("sp500.csv",index_col="Symbol",usecols=[0,2,3,7])
print(sp500.head)
# view the number of rows
print(len(sp500))
# view the dimensions
print(sp500.shape) # should be 500 x 3
print(sp500.size) # size returns row count x column count, i.e. 500*3
p... |
#!/usr/bin/python3
import re
pattern = re.compile (r'(a|b)+')
list = pattern.findall('aba')
print("Result using r'(a|b)+' on 'aba' :", list)
"""
(a|b)+ will be a repeated capturing group due to the "+", and only capture the last iteration.
So it matches the last a.
Remove + to capture all characters. In addition th... |
#!/usr/bin/python3
import re
pattern = re.compile(r'(\w+) (\w+)?')
text = "Hello world"
match = pattern.search(text)
print("match.groups() ", match.groups())
print("match.group(0) ", match.group(0))
print("match.group(1) ", match.group(1))
print("match.group(2) ", match.group(2))
#print("match.group(3) ", match.group... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.