text stringlengths 37 1.41M |
|---|
#81
# Time: O(logn)
# Space: O(1)
# Follow up for "Search in Rotated Sorted Array":
# What if duplicates are allowed?
#
# Would this affect the run-time complexity? How and why?
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
# (i.e., 0 1 2 4 5 6 7 might become 4 5 ... |
#111
# Time: O(n)
# Space: O(h), h is height of binary tree
# Given a binary tree, find its minimum depth.
#
# The minimum depth is the number of nodes along the shortest path
# from the root node down to the nearest leaf node.
class TreeNode():
def __init__(self,val):
self.val=val;
self.rig... |
#122
# Time: O(n)
# Space: O(1)
# Say you have an array for which the ith element
# is the price of a given stock on day i.
# Design an algorithm to find the maximum profit.
# You may complete as many transactions as you like
# (ie, buy one and sell one share of the stock multiple times).
# However, you may not e... |
#143
# Time: O(n)
# Space: O(1)
# Given a singly linked list L: L0→L1→…→Ln-1→Ln,
# reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
#
# You must do this in-place without altering the nodes' values.
#
# For example,
# Given {1,2,3,4}, reorder it to {1,4,2,3}.
class ListNode():
def __init__(self,val):
self.val=... |
#7
# Space: O(1)
# Given a 32-bit signed integer, reverse digits of an integer.
#
# Example 1:
# Input: 123
# Output: 321
# Example 2:
# Input: -123
# Output: -321
# Example 3:
# Input: 120
# Output: 21
#
# Note:
# Assume we are dealing with an environment
# which could only hold integers within the 32-bit signed... |
#285
# Time: O(h) height of BST
# Space: O(1)
# Given a binary search tree and a node in it,
# find the in-order successor of that node in the BST.
#
# Note: If the given node has no in-order successor
# in the tree, return null.
class TreeNode():
def __init__(self,val):
self.val=val;
self.... |
#206
# Time: O(n)
# Space: O(1)
# Reverse a singly linked list.
class ListNode():
def __init__(self,val):
self.val=val
self.next=None
def __repr__(self):
return '{}->{}'.format(self.val,repr(self.next))
class ListSol():
def reverseListI(self,head):
dummy=ListNode(... |
#71
# Time: O(n)
# Space: O(n)
# Given an absolute path for a file (Unix-style), simplify it.
#
# For example,
# path = "/home/", => "/home"
# path = "/a/./b/../../c/", => "/c"
class stackSol():
def simplifyPath(self,path):
split_path=path.split('/')
simplify_path=[]
for path_elem in... |
#Generate a random number with a seed between a range of two numbers - Both Integer and Decimal
from random import seed
from random import randint
from random import uniform
class GenNumWithSeed:
@staticmethod
def random_int(a, b, nut):
seed(nut)
if isinstance(a, float):
return Ge... |
def median(a, b, c, d, e):
try:
a = int(a)
b = int(b)
c = int(c)
d = int(d)
e = int(e)
median_list = [a, b, c, d, e]
length = len(median_list)
sorted_median_list = sorted(median_list)
return sorted_median_list[2]
except ZeroDivisionError:
... |
"""Openrouteservice API function to perform API calls in the Truck class."""
import requests
from config import ORS_URL, ORS_HEADERS
def get_direction(start: dict, end: dict):
"""Make API call to OpenRouteService API to generate directions.
Args:
start (dict): Starting point, contains keys lat and l... |
def eratosthenes_sieve(N):
# Increment once in order to remove redundancy
N += 1
prime = [True] * (N)
primes_tab = [2]
for c in range(3, N, 2):
if prime[c] == True:
primes_tab.append(c)
# Mark all multiples of c as composite
for mul_c in range(c*c, N, c):
... |
import asyncio
#To inicate that the function coroutine we must add async before the def
async def foo():
for i in range(10):
#Await means to wait until that line of code is finished
#Note that we can only put await if it's in a coroutine function
await asyncio.sleep(1)
print(1)
asyn... |
import math
r = int(input('r: '))
s = round(math.pi * r * r, 3)
p = round(2 * math.pi * r, 3)
print('S: ', s)
print('P: ', p)
|
year = int(input('input an year: '))
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print(year, 'liigaasta')
else:
print(year, 'pole liigaasta') |
"""
用类和面向对象的思想,“描述”生活中任意接触到的东西
(比如动物、小说里面的人物,不做限制,随意发挥),数量为5个。
"""
#描述狗的类
class Dog:
#构造方法,传入种类,颜色
def __init__(self,dog_type,dog_colour):
#种类
self.dog_type = dog_type
#颜色
self.dog_colour = dog_colour
#看门
def watch_door(self):
print(f"{self.dog_type}可以在家看门")
... |
from random import randint
# Number of words you want to get in your password
word_num = 5
# Import and organize the dictionaly of words
d = {}
with open("diceware.wordlist.asc", "r") as f:
for item in f:
ssplit = item.split()
key = ssplit.pop(0)
d[key] = ssplit
# Generate and print!
random_num_se... |
# A few handy functions
# Converts input to lower case, splits words into a list
def get_smart(prompt):
raw_input = input(prompt)
# Convert the input to lower case:
smooth_input = raw_input.lower()
# Convert the lower case input into a list:
input_list = smooth_input.split()
# print(input_list) # for testin... |
# -*- coding: utf-8 -*-
import re
def word_length(sentence):
return sentence.count(' ') + 1
def tokenize_sentence_and_filte_tokens(
text_str,
tokenizer,
token_filters,
):
tokenized_text_lst = tokenizer.cut(text_str)
filted_tokens = []
for token in tokenized_text_lst:
... |
# Caesar cipher
import string
def encrypt(s, n):
letters = string.ascii_uppercase
s_encrypted = ""
key = {}
for i in range(0, 26):
key.update({letters[i]:letters[(i+n)%26]})
for v in s.upper():
s_encrypted+=key[v]
return s_encrypted
if __name__ == "__main__":
s = raw_input("Enter a string to encrypt: ")
n ... |
n = int(input("Enter rows: "))
for i in range(0, n):
for j in range(0, i+1):
print("x", end="")
print()
print("Hola mundo") |
from ps4a import *
import time
# Computer chooses a word
def compChooseWord(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
This word should be calculated by considering all the words
in the wordList.
If no words in the w... |
"""
Faça uma prova de matemática para crianças que estão aprendendo a somar números inteiros menores que 100.
Escolha números aleatórios entre 1 e 100, e mostre na tela a pergunta: qual é a soma de a + b, onde a e b
são os números aleatórios. Peça a resposta. Faça cinco perguntas ao aluno, e mostre para ele as pergunta... |
"""
Leia um valor em segundos, e imprima-o em horas, minutos e segundos.
"""
total_segundos = int(input('digite um valor em segundos: '))
segundo = total_segundos % 60
minuto = (total_segundos // 60) % 60
hora = (total_segundos // 60) // 60
print(f'{hora} hora(s), {minuto} minuto(s) e {segundo} segundo(s)')
|
"""
Faça um programa que receba dois numeros e mostre o maior. Se por acaso, os dois
numeros forem iguais, imprima a mensagem 'Numeros iguais'.
"""
num1 =int(input('digite um numero: '))
num2 =int(input('digite outro numero: '))
if num1 > num2:
print(f'O numero {num1} é maior.')
elif num1 == num2:
print(f'Nume... |
"""
Faça um programa que leia 10 inteiros positivos, ignorando não positivos, e imprima sua média.
"""
soma = 0
cont = 0
for i in range(10):
number = int(input(f'digite o valor {i+1}/10: '))
if number >= 0:
soma += number
cont += 1
print(f'A media dos valores positivos eh igual a {soma/cont:.2f}... |
"""
Faça um programa que receba um numero inteiro e verifique se este numero é par ou impar.
"""
num = int(input('digite um numero: '))
if num % 2 == 0:
print('O numero digitado é par.')
else:
print('O numero digitado é impar.')
|
"""
Faça um programa que leia um número inteiro positivo impar N e imprima todos os
numeros impares de N até 1 em ordem decrescente.
"""
num = 60
for i in range(num-1, 0, -2):
print(i)
|
"""
Faça um programa que leia 10 inteiros e imprima sua média.
"""
soma = 0
for i in range(10):
number = int(input(f'digite o valor {i+1}/10: '))
soma += number
print(f'A media dos valores eh igual a {soma/10:.2f}') |
"""
Faça um programa que mostre ao usuário um menu com 4 opções de operações matemáticas
(as básicas, por exemplo). O usuário escolhe uma das opções e o seu programa então pede
dois valores numéricos e realiza a operação, mostrando o resultado e saindo.
"""
import os
print('ESCOLHA UMA DAS OPÇÕES A SEGUIR:')
print('[1... |
"""
Escreva um programa que, dado o valor da venda, imprima a comissão que deverá ser paga
ao vendedor. Para calcular a comissão, considere a tabela abaixo:
VENDA MENSAL COMISSÃO
Maior ou igual a R$100.000,00 R$700,00 + 16% das vend... |
"""
Faça um programa que leia um número inteiro positivo N e imprima todos os
numeros naturais de N até 0 em ordem decrescente.
"""
num = 60
for i in range(num, -1, -1):
print(i)
|
"""
Leia a temperatura em graus Fahrenheit e apresente-a em graus Celsius.
A fórmula de conversão é: C = 5.0 * (F - 32.0) / 9.0, sendo C a temperatura em Celsius
e F a temperatura em Fahrenheit .
"""
fahrenheit = float(input('digite a temperatura em graus Fahrenheit: '))
celsius = 5.0 * (fahrenheit - 32.0) / 9.0
pr... |
#Faça a leitura de três valores e apresente como resultado a soma dos quadrados dos três valores obtidos.
num1 = 12
num2 = 15
num3 = 18
resultado = (num1**2) + (num2**2) + (num3**2)
print(resultado)
|
"""
Faça um programa que leia um valor N inteiro e positivo, calcule e mostre o valor E,
conforme a fórmula a seguir:
E = 1+1/1! + 1/2! + 1/3! +...+1/n!
"""
def fatorial(num):
n = num
fat = 1
i = 2
while i <= n:
fat = fat * i
print(fat)
i += 1
return fat
print(0%2)
|
"""
Leia um valor de área em hectares e apresente-o convertido em metros quadrados m². A fórmula
de conversão é: M = H * 10000, sendo M a área em metros quadrados e H a área em hectares.
"""
hectares = float(input('digite um valor de área em hectares: '))
m2 = hectares * 10_000
print(f'o valor convertido em metros q... |
# Leia um numero inteiro e imprima a soma do sucessor de seu triplo com o antecessor de seu dobro.
num = int(input('digite um numero inteiro: '))
print(f'a soma do sucessor de seu tripo com o antecessor do seu dobro é igual a {(num*3+1)+(num*2-1)}')
|
class Parent():
def __init__(self, last_name, eye_color):
print("Parent Constructor called")
self.last_name=last_name
self.eye_color=eye_color
def show_info(self):
print(self.last_name)
print(self.eye_color)
class Child(Parent):
def __init__(self, last_name, eye_col... |
class Jarra:
def __init__(self,cap):
self.capacidad=cap
self.contenido=0
def llena(self):
self.contenido=self.capacidad
def vacia(self):
self.contenido=0
def capacidad(self):
return self.capacidad
def contenido(self):
return self.contenido
de... |
#leet code - decode string - 394 - https://leetcode.com/problems/decode-string/
#Time complexity -O(N)
#space complexity-O(N)
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack=[]
currstr=""
currnum=""
for i in ... |
class Solution:
def findMin(self, nums: List[int]) -> int:
l, r = 0, len(nums) - 1
while l < r:
mid = l + (r - l) // 2
if nums[mid] > nums[r]:
l = mid + 1
else:
r = mid
# At this point, left and right converge to... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
lenA = self.calculate_len(headA)
lenB = self.calculate_len(headB)
... |
#multiple for to build comprehensive
a = [(x,y) for x in range(5) for y in range(5) if (x+y) % 2 == 0]
print(a)
b = [(x,y) for x in range(5) for y in range(5) if(x+y) % 2 == 0 and x!=y]
print(b) |
number_list = [3, 41, 12, 9, 74, 15]
count = 0
total = 0
for number in number_list:
count += 1
total += number
print(number)
print("Count: ",count)
print("Total: ",total) |
# d = {
# "Name": "Guido",
# "Age": 56,
# "BDFL": True
# }
# for a,b in d.items():
# print(a,b)
# for a in d.keys():
# print(a)
# for b in d.values():
# print(b)
# #create a comprehesive list
# my_list = [x**3 for x in range(1,11) if x % 2 != 0]
# my_list = [x**3 for x in range(1,11) if x % 4 == 0]
# ... |
import pandas as pd
df = pd.read_csv('glassdoor_jobs.csv')
df.head()
#cleaning things to do
#salary parsing
#company name text only
#state field and
#age of company
#parsing of job description (python etc)
#Salary parsing
df['hourly'] = df['Salary Estimate'].apply(lambda x: 1 if 'per hour' in x.lower() else 0)
df['em... |
from sys import stdin
class ComplexNumber:
def __init__(self, real=0, imaginary=0):
self.real = real
self.imaginary = imaginary
def __add__(self, another):
return ComplexNumber(self.real + another.real,
self.imaginary + another.imaginary)
def __sub__(... |
ulang="y"
while ulang=="y" or ulang =="Y":
print("===========================")
print(" Pembelian printer")
print("===========================")
u=1
u =input(" Masukkan Banyak Printer = ")
n=int(u)
harga = n * 660000
print(" Total Harga Pembelian Printer= Rp.",harga)
ulang ... |
class Application():
def sum(self,n,m):
return n+m
def subtract(self,n,m):
return n-m
def multiply(self,n,m):
return n*m
def divide(self,n,m):
return n/m
def power(self,n,m):
p=1
if m >=0:
for i in range(m):
p=p*n
el... |
print(input_shape)
input_img = Input(shape=input_shape)
network = Conv2D(32, kernel_size=(3, 3), activation='relu',input_shape=input_shape) (input_img)
network = Conv2D(64, kernel_size=(3, 3), activation='relu') (network)
network = Flatten() (network)
network = Dense(512, activation='relu') (network)
network = Dense(... |
from collections import MutableSequence
class Node(object):
"""
A node that holds a value and possibly connects to a next node.
"""
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
class LinkedList(MutableSequence):
"""
A list where items ar... |
from day5_data import DATA as DATA
# Faster to loop over entire data and mark pairs for deletion than
# deleting them immediately when they are detected.
def reduce(data):
changed = True
while changed:
changed = False;
for i in range(1, len(data)):
if data[i] != data[i-1] and data[i... |
from day1_data import DATA as DATA
def main(data):
freq = 0;
hist = {}
hist[freq] = True
while True:
for i in data:
freq += i
if freq in hist:
print "Freq: " + str(freq) + " appeared twice"
return
hist[freq] = True
if __name... |
import csv
def read_data():
patches = []
with open('day3_data.txt') as csvfile:
reader = csv.reader(csvfile, delimiter = " ")
for row in reader:
coord = row[2].split(',')
x = int(coord[0])
y = int(coord[1].split(':')[0])
coord = row[3].split('x')
... |
def palindrome(str):
split_str = list(str)
print split_str
my_dict = {}
for i in range(0, len(split_str)):
#print split_str[i]
bool = False
if split_str[i] in my_dict:
my_dict[split_str[i]] = my_dict[split_str[i]]+1
else:
my_dict[split_str[i]] = 1
print my_dict
countone = 0
... |
import pandas as pd
import numpy as np
import sklearn
from sklearn import linear_model
from sklearn.utils import shuffle
import matplotlib.pyplot as pyplot
import pickle
from matplotlib import style
#read data and each data value is seperated by a comma(",")
data = pd.read_csv("heart.csv",sep=",")
"""
Binary
0=No,Wom... |
file = open('input.txt')
lines = file.read().splitlines()
trees = 0
position = 3
for line in lines[1:]:
if line[position] == '#':
trees = trees + 1
position = (position + 3) % 31
print(trees) |
def to_char_arrays(text, w):
"""sets the words from input string into one or more character
arrays of length w
:param text: input string
:param w: maximum length of array
:type text: str
:type w: int
:return list of character arrays
:rtype list of str
"""
words = text.split()
... |
__author__="JimmyMo"
__date__ ="$Aug 31, 2013 8:33:23 PM$"
list = [123, "abc", 1.23]
list.append('ni')
p = list.pop(0)
list.sort()
print list;
list.reverse()
list.insert(0, 'aaa')
print list.count('aaa')
print list;
print p;
print range(len(list))
for i in list:
print i
for i in range(len(list)):
print i
prin... |
"""Для списка реализовать обмен значений соседних элементов, т.е.
Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте.
Для заполнения списка элементов необходимо использовать функцию input()."""
input_list = input("Введите через пробел э... |
import pygame
pygame.init()
gameDisplay = pygame.display.set_mode((800,600))
#pygame.display.set_mode sets the game window size.
#Arguments are passed in as a tuple
pygame.display.set_caption("The Game Name")
#pygame.display.set_caption sets the game display name
#The name appears on the game display window
clock... |
import math
print("Input de radius of a circle: ", end="")
r = float(input())
print("The area of a circle of radius", str(r), "is: ", math.pi*r**2) |
s = input()
left = int(s[:2])
right = int(s[2:])
ans = "NA"
if 0 < left <13:
if 0 < right < 13:
ans = "AMBIGUOUS"
else:
ans = "MMYY"
else :
if 0 < right < 13:
ans = "YYMM"
print(ans)
|
n, a, b, c, d = map(int, input().split())
string = input()
if "##" in string[a-1:c] or "##" in string[b-1:d]:
print("No")
elif c < d:
print("Yes")
else :
if "..." in string[b-2:d+1]:
print("Yes")
else :
print("No")
|
from collections import deque
class vertex:
def __init__(self, mark, val=None, firstEdge=None):
self.mark = mark
self.val = val
self.firstEdge = firstEdge
self.isVisited = False
def __str__(self):
try:
int(self.mark)
return 'v' + str(self.mark)
... |
#!/usr/bin/env python
# -*-coding:UTF-8-*-
#多态:不同对象对同一方法响应不同的行动
#斐波那契数列/黄金分割数列
def num_1 ():
a,b = 0,1
while b < 70:
print(b,end=' ')
#print(a)
a,b = b,a+b
#num_1()
# def fad(n):
# if n==1 or n==2:
# return 1
# else:
# return fad(n-1)+fad(n-2)
... |
import collections
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 树其实相当于对列表的一个扩充
import collections
class Node(object):
def __init__(self, item):
self.item = item
# 不同于链表的是,连接区域不同,二叉树有左右... |
from Linked_list.SingleLinkList import SingleNode, SingleLinkList
class Solution:
# 反转链表
def reverseList1(self, head):
if head is None:
return None
pPre = None
while head != None:
pNext = head.next
# 切换head的下一个节点,重新指向前一个元素, pre,head 分别向后移
... |
def merge_sort(alist):
n = len(alist)
if n <= 1:
return alist
mid = n//2
# left采用归并排序后形成的有序的新的列表
left_li = merge_sort(alist[:mid])
# right 采用归并排序后形成的有序的新的列表
right_li = merge_sort(alist[mid:])
# 将两个有序的子序列合并成一个新的整体
# merge(right,left)
left_pointer, right_pointer = 0, 0
... |
class SingleNode(object):
"""单链表的节点"""
def __init__(self, item):
# item存放数据元素
self.item = item
# next 存放下一个节点的标识
self.next = None
class SingleHasCycleLinkList():
# 对象属性
def __init__(self, node=None):
# 可以设置默认参数
self._head = node
if node:
... |
class Solution():
def isIsomorphic(self,str,t):
if s.strip()=='' or t.strip()=='':
return False
dict1 = {}
dict2 ={}
for i in range(len(str)):
if (str[i] in dict1 and dict1[str[i]] != t[i]) or t[i] in dict2 and dict2[t[i]] != str[i]:
return Fa... |
class Node(object):
"""多层双向链表的节点"""
def __init__(self, item):
# item存放数据元素
self.item = item
self.next = None
self.prev = None
self.child = None
class Solution:
def flatten(self, head: 'Node') -> 'Node':
pre = None
self.recursive(head, pre)
r... |
"""! @brief Defines the Error classes"""
##
# @file error_led.py
#
# @brief Defines the error class for computing the error between the sensors
#
# @section description_error Description
# Defines the class and function for computing the error between the sensors and returns the good sensor id
#
# @section libraries_se... |
#!/usr/bin/env python
# coding: utf-8
# This project will explore a sample of German Ebay auto classifieds. The data needs to be cleaned and then analyzed. This project should help me to practice and better understand the details of working with pandas and cleaning data.
# In[86]:
import pandas as pd
import numpy... |
import numpy as np
import cv2
import myLogger as log
def _draw_dotted_line(img, pt1, pt2, color):
"""
Draws a dotted line between to points on an image
:param img: The image to draw on
:param pt1: Point 1 of the line (x, y)
:param pt2: Point 2 of the line (x, y)
:param color: The color of the ... |
a=int(input('a='))
b=int(input('b='))
kup=1
if a<b:
for i in range(a,b+1):
kup *= i
print('Ko\'paytmasi',kup)
else:
print('A<B shartni qanoatlantirmaydi')
|
# -*- coding: utf-8 -*-
"""
For32. n butun soni berilgan (n > 0). Quyidagi ketma – ketlikning dastlabki n ta hadini chiqaruvchi
programma tuzilsin.
A
0 = 1; AK = (AK-1 + 1) / K; K = 1, 2, …
Created on Fri Jun 25 18:33:00 2021
@author: Mansurjon Kamolov
"""
n = int(input('n='))
a=1
for i in range(1,n+1)... |
# -*- coding: utf-8 -*-
"""
For16. n butun soni va a haqiqiy soni berilgan (n > 0). Bir sikldan foydalanib a ning 1 dan n gacha
bo’lgan barcha darajalarini chiqaruvchi programma tuzilsin.
Created on Thu Jun 24 19:37:20 2021
@author: Mansurjon Kamolov
"""
a = float(input('a = '))
n = int(input('n = '))
ku... |
def largest_matrix(arr):
# Write your code here
if len(arr) == 0 or len(arr[0]) == 0:
return 0
cache = [[0 for i in range(len(arr[0]))] for j in range(len(arr))]
for i in range(len(arr)):
cache[i][0] = arr[i][0]
for j in range(len(arr[0])):
cache[0][j] = arr[0][j]
lar... |
#转义序列:\n \t \r \' \"...
days = 'Mon Tue Wen Thu Fri Sat Sun'
months = '\nJan\nFeb\nMar\nApr\nMay'
print('Here are the days:', days)
print('Here are the months:', months)
#长字符串以行打印
print('''
There's something going on here.
With the three double_quotes.
We'll be able to type as much as we can.
Even 4 lines if we w... |
#复习各种符号
#python中的关键字:
#raise,yield,lambda
#python数据类型
#strings,numbers,floats,lists,dicts,bytes,None,False,True
#转义序列
#\a:响铃
#\b:退格
#\f:换页
#\r:回车
#\v:垂直制表符
#老式字符串格式方法,'%占位符'%替换内容
#替换整数
print('>>> ', '%d' % 25)
print('>>> ', f'{25}')
#替换浮点数
print('>>> ', '%.3f' % 3.1415926)
#替换字符串
print... |
import os
# define function
def read_file(filename):
log = []
with open(filename, 'r', encoding='UTF-8-SIG') as f:
for line in f:
log.append(line.strip())
return log
def formatting(log):
person = None # just to prevent if there is no Allen or Tom in first line of chatlog
# i... |
# 0702_while.py
password = 12345678
running = True
while running:
guess = int(input('Enter password: '))
if guess == password:
print('Welcome to Facebook!')
running = False
else:
print('Wrong password.')
else:
print('Not logg... |
# 0502_print.py
# Fun with print()
print('a', end = '\t')
print('b', end = '\t')
print('c', end = '\t')
print('\nNew lines are \n. Understand?\n')
print(r'\nNew lines are \n. Understand?\n')
myName = 'Aaron'
print(myName)
_myAge = 41
print(_myAge)
mySong = 'Blueming'
print(mySong)
# Variables in one line (;)
i = ... |
# 0501_format.py
'''This is a long comment.
We will learn `format` string.
Ready?
'''
age = 41
name = "Aaron"
print('{1} is {0} years old.'.format(age, name))
print(name + ' is ' + str(age) + ' years old.')
print('{name} is {age} years old.'.format(age = 28, name = 'IU'))
name2 = 'IU'
song = '가을아침'
print(f'{name2... |
# my_pizza.py
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}cm pizza with: ")
for t in toppings:
if t.lower() == 'myulchi' or t.lower() == 'pineapple' or t.lower() == 'gochu':
print(f"- NO {t}!")
else:
... |
# 1202_robots.py
class Robot:
pop = 0 # 인구
def __init__(self, name):
self.name = name
print('{} 만드는 중'.format(self.name))
Robot.pop += 1
def die(self):
print('{} 꺼지고 있어요.'.format(self.name))
Robot.po... |
# ECar = 전기차
from Car import Car
class ECar(Car):
"""ECar is a type of Car."""
def __init__(self, make, model, year, battery_size=75):
super().__init__(make, model, year)
self.battery = battery_size
def get_battery(self):
print(f"Your battery is a {self.battery}-kWh battery.")
... |
"""
Level order traversal of a tree is breadth first traversal for the tree.
printLevelorder(tree)
1) Create an empty queue q
2) temp_node = root /*start from root*/
3) Loop while temp_node is not NULL
a) print temp_node->data.
b) Enqueue temp_node’s children (first left then right children) to q
c) Dequeue a node from... |
# In this lecture we'll cover the usage of the with statement.
# The with statement allows to close a file without using the close method.
# The with statement defines a block, which will close the file once left.
# In the block defined the variable file can be used
with open("18_Text_File.txt", 'a') as file:
fil... |
# EX 07: Translating addresses into geographic coordinates
# The process of translating an address to a pair of coordinates is called
# geo-coding. The reverse mechanism is called reverse geo-coding
# To do this exercise you need to install the Geopy library
# https://github.com/geopy/geopy
import pandas
import geopy
... |
# In this lecture we are going to cover the different ways to import
# datasets in pandas. We'll use file such as .xlsx, .csv, .json etc.
# You can find some example files in the Resources folder.
# In order to have a better data visualization, it is recommended to use
# the Jupyter Notebook: http://jupyter.org/
# F... |
# In this simple lesson we are going to print something on screen
# We use the built in print function
print("Hello world!")
v = 3
v = v + 1
print("Second hello world")
|
# In this lecture we'll cover the fundamentals of loops.
# A loop is basically a way to execute a statement multiple times.
# Loops allow to save a lot of code, and avoid some replications.
# In Python there are two different loops: for and while
emails = ["foo@email.com", "me@gmail.com", "you@hotmail.com"]
# If we w... |
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a ... |
import os
os.chdir('E:\Datacamp\Python\Introduction to database in Python')
from sqlalchemy import create_engine, select
engine = create_engine("sqlite:///census.sqlite")
connection = engine.connect()
# Import packages
from sqlalchemy import MetaData, Table
# Creaate metadata
metadata = MetaData()
# Reflect census ta... |
import datetime
import math
database ={}
balance = 100
def basicMenu():
print('These are the available options')
print('1. Withdrawl')
print('2. Deposit')
print('3. Comlpaint')
selectedOption = int(input('Please selct an opton: '))
return selectedOption
def option(choice):
global balance
... |
# lamada multiplication
# lamda_multiplication.py
#Lambda functions can take any number of arguments:
#Multiply argument a with argument b and return the result:
# [Running] python -u "/Users/anupama/Desktop/python/lamada_multiplication.py" 30
x = lambda a, b : a * b
print(x(5, 6)) |
import re
def unique_in_order(iterable):
c = re.sub(r'(\S)\1+', '\\1', str(iterable))
if c.isdigit():
d = list(c)
d = [int(i) for i in d]
print(d)
else:
print(list(c))
unique_in_order('123777')
unique_in_order('ABCDAB')
#from itertools import groupby
... |
with open("check64.txt") as f:
check=f.read()
with open('out64.txt') as f:
out=f.read()
def encrypt(text, crypto):
key=""
i=0
for x in text:
key+=chr(ord(crypto[i])-ord(x))
i+=1
print(key)
def decrypt(text,key):
keylen = len(key)
keyPos = 0
decrypted = ""
for x in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.