text stringlengths 37 1.41M |
|---|
# generate list of all odd numbers starting at 3 up to and including bound
def odds_list(bound):
"""
Returns list of odds from 3 to bound (inclusive if bound is odd).
"""
odds = [(x*2 + 1) for x in range(1,bound//2)]
if bound % 2 == 1:
odds.append(bound)
return odds
#print(generate_odds(11))
def prim... |
#csv-comma seperated value
#writin the data in csv file-->csv.writer(),to read csv.reader()
"""import csv
with open("sales.csv","w",newline='') as f: # if we dont give newline='' it will created a blank line on csv
w=csv.writer(f) # to write
w.writerow(["product_name","product_id","product_cost"]) #header
... |
"""basic data types
int
float
complex
string
"""
#float
x=2.1e78 #exponential form where big value is storing in less momeory
print(x)
print(type(x))
#complex number(X+YJ)whereY is imaginary part and X is real part
x=2+3j
print(x)
print(type(x))
#============================================================
x,y=0b11... |
# Programming in Python 3, pag. 41
# Nùmeros Ascii tomados de: https://gist.github.com/yuanqing/ffa2244bd134f911d365
import sys
Zero = [" 0000 ", "00 00", "00 00", "00 00", " 0000 "]
One = ["1111 ", " 11 ", " 11 ", " 11 ", "111111"]
Two = [" 2222 ", "22 22", " 22 ", " 22 ", "222222"]
Three = [" 3333 ", ... |
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 + -n2
def mul(n1, n2):
res = 0
for _ in range(abs(n2)):
if n2 > 0:
res += n1
elif n2 < 0:
res = sub(res, n1)
else:
return 0
return res
def div(n1, n2):
count = 0
res = ab... |
import itertools
strng = raw_input("Enter small string > ")
perms = list(itertools.permutations(strng))
perm_strings = [''.join(x) for x in perms]
for permstr in perm_strings:
print(permstr)
|
import sys
def operate(symbol, n1, n2):
if symbol == "*":
return int(n1) * int(n2)
elif symbol == "/":
return int(n1) / int(n2)
elif symbol == "+":
return int(n1) + int(n2)
elif symbol == "-":
return int(n1) - int(n2)
# 5 * 5 + 3 - 2 -> ["5 * 5", "+ 3", " - 2"]
# doesn... |
count_bottles = "{} bottles of beer on the wall, {} bottles of beer."
remove_bottle = "Take one down and pass it around, {} bottles of beer on the wall."
no_more = "No more bottles of beer on the wall, no more bottles of beer."
finisher = "Go to the store and buy some more, 99 bottles of beer on the wall."
if __name_... |
import itertools
import sys
# takes a list of ints + target number.
# --> 2 ints that sum to target number, or None
def pair_sums(ls):
for pair in itertools.permutations(ls, 2):
yield (pair[0] + pair[1], pair)
target = int(sys.argv[1])
ls = map(int, sys.argv[2].split(" "))
print next((pair[1] for pair... |
from itertools import chain
def split_in_chunks(ls, size):
newls = []
for i in xrange(0, len(ls), size):
newls.append(ls[i:i+size])
return newls
def reverse_chunks(chunks):
return [x[::-1] for x in chunks]
def flatten_chunks(chunks):
return list(chain(*chunks))
chunks = split_in_chunks(r... |
import datetime
import sys
def int2day(i):
days = ["Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"]
return days[i]
if __name__ == '__main__':
try:
day = int(sys.argv[1])
month = int(sys.argv[2])
year = int(sys.argv[3])
time = dateti... |
from random import randint, sample
from typing import Iterable
class Card:
def __init__(self):
self._rows = make_lotto_card()
self._numbers = set(n for row in self._rows for n in row if n != 0)
self._marked = set()
def __contains__(self, item):
return item in self._numbers
... |
'''
A useful pd.Series feature is that index labels align for arithmetic
Series arithmetic is similar to a join on dB tables.
'''
import pandas as pd
dictionary = {'California':40000000, 'Texas': 29000000, 'Florida': 22000000, 'New York':19000000}
dict2 = {'California':40000000, 'Florida':22000000, 'Utah':320... |
'''
Ranking assigns ranks from 1-N, where N is the number of valid data points in an array (along one axis)
NOTE: By default, equal values are assigned a rank that is the average of the ranks of those values.
'''
import numpy as np
import pandas as pd
series = pd.Series([7, -5, 7, 4, 2, 0, 4])
def showRank... |
'''
To analyze nutrient data, the nutrients for each food are being assembled into
a single large table. This requires multiple steps:
1) Convert each list of food nutrients to a DataFrame
2) Add a column for the food id
3) Append the DataFrame to a list
4) Concatenate the two DataFrames together
'''
import jso... |
import itertools
firstLetter = lambda x: x[0]
names = ['Alan', 'Adam', 'Wes', 'Will', 'Albert', 'Steven']
for letter, names in itertools.groupby(names, firstLetter):
print(letter, list(names))
'''
Error about itertools is inaccurate. Could not find problem online with pylint
Output:
A ['Alan', '... |
# Thenea Sun
# Dec. 18th
# A project about breakout game
import pygame, sys
from pygame.locals import *
import block
import random
pygame.init()
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 800
X_SPEED = 3
Y_SPEED = 4
main_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 32, 0)
pygame.display.set_caption("Break ... |
# Softmax's goal is to give catagories to different classes that
# are non negative. It accomplishes this by using exponents
# the weights will be between 0 and 1 and add up to 1
import numpy as np
# Write a function that takes as input a list of numbers, and returns
# the list of values given by the softmax function... |
# We use variables to store data (int, string, ...,etc) in them
Fname= "Najeeb"
Anystring= "started to learn python with SaudiDevOrg."
# We use this character(+) to concatenate two or more strings
print(Fname +" "+ Anystring)
# Also we use this character(+) to add two or more numbers
num1=100
num2=500
print("The resu... |
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_par... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import re
def register():
SpecialChar = ['$','@','#','%']
db = open('database.txt','r')
Username = input("Create username: ")
Password = input("Create password: ")
Password1 = input("Confirm password: ")
d = []
f = []
for i in db:
... |
# Remember that Control+Alt+N will run code in Visual Studio Code
print "Hello"
print 'Hello'
# print Hello won't work because here Python sees Hello as a varible which we have not defined
hello = "Howdy"
print hello # this will work
# valid strings quiz
# Which are valid strings?
# My answer was "Ada" ... |
# Greatest Quiz
# Define a procedure, greatest,
# that takes as input a list
# of positive numbers, and
# returns the greatest number
# in that list. If the input
# list is empty, the output
# should be 0.
# My answer
def greatest2(list_of_numbers):
biggest = 0
for each in list_of_numbers:
... |
elements = {}
elements['H'] = {'name': 'Hydrogen', 'number': 1, 'weight': 1.00794}
elements['He'] = {'name': 'Helium', 'number': 2, 'weight': 4.002602, 'noble gas': True}
print elements['H'] # print entire value associated with 'H'
print elements['H']['name'] # print one particular value from the 'H' dictiona... |
# Udacify Quiz
# Define a procedure, udacify, that takes as
# input a string, and returns a string that
# is an uppercase 'U' followed by the input string.
# for example, when you enter
# print udacify('dacians')
# the output should be the string 'Udacians'
# MY ANSWER
def udacify(input):
return 'U... |
x=input("请输入累加值上限:")
while not str.isdecimal(x):
print("你是来搞笑的吧,输入数字呀!")
x = input("请输入累加值上限:")
t=int(x)
s=0
for i in range(1,t+1):
s+=i
print(s) |
from math import sqrt, pi, cos, sin, radians
from random import random, randint
from heapq import nlargest
from server.product import Product
def most_popular(products, n):
"""
Returns the `n` most popular products from `products`
"""
return nlargest(n, products, lambda p: p.popularity)
def gen... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 3 10:51:43 2021
@author: luciano
"""
def fatorial(n, show = False):
"""
Parameters
----------
n : int
DESCRIPTION: Número a ser calculado.
show : bool (opcional)
DESCRIPTION: Mostrar ou não a conta.
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 16 09:13:47 2021
@author: luciano
"""
num = []
while True:
n = int(input('Digite um valor: '))
if n not in num:
num.append(n)
print('Valor adicionado com sucesso...')
else:
print('Valor duplicado não vou a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
=============================================
|| Created on Thu Sep 16 09:13:50 2021 ||
|| @author: luciano ||
=============================================
"""
lista = []
for i in range(0, 5):
n = int(input('Digite um valor: ') )
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 14 09:02:26 2020
@author: luciano
"""
a = input('Digite algo: ')
print('O tipo primitivo desse valor é: ', type(a))
print('So tem espaços ? ', a.isspace())
print('É um número ? ', a.isnumeric())
print('É alfabetico ? ', a.isalpha())
print('É alfanum... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 6 10:35:40 2021
@author: luciano
"""
def escreve(msg):
tam = len(msg) + 4
print('~'*tam)
print(f' {msg}')
print('~'*tam)
frase = str(input('Qual frase você quer escrever ? : '))
escreve(frase) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 7 21:50:49 2021
@author: luciano
"""
from datetime import date
ano = int(input('Que ano você quer analisar ? Digite 0 para analisar o ano atual.'))
if ano == 0:
ano = date.today().year
if ano % 4 == 0 and ano %100 !=0 or ano %400 == 0:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 16:07:42 2020
@author: luciano
"""
n = int(input('Entre com um número para ver sua tabuada: '))
print('-' * 12)
print('{} x 1 = {}'.format(n,n))
print('{} x 2 = {}'.format(n,2*n))
print('{} x 3 = {}'.format(n,3*n))
print('{} x 4 = {}'.format(n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 8 09:17:22 2021
@author: luciano
"""
from random import randint
computador = randint(0,10)
print('Sou seu computador... Acabei de pensar em um número entre 0 e 10.')
print('Será que você consegue adivinhar qual foi ?')
acertou = False
n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 15:53:42 2020
@author: luciano
"""
m = float(input('Um distancia em metros: '))
print('A medida de {}m corresponde a: '.format(m))
print('\n{}km'.format(m/1000))
print('\n{}hm'.format(m/100))
print('\n{}dam'.format(m/10))
print('\n{}dm'.format(10... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 19:11:31 2021
@author: luciano
"""
from random import shuffle
n1 = str(input('Primeiro aluno: '))
n2 = str(input('Segundo aluno: '))
n3 = str(input('Terceiro aluno: '))
n4 = str(input('Quarto aluno: '))
alunos = [n1, n2, n3, n4]
shuffle(alu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 29 13:17:53 2021
@author: luciano
"""
pessoa = {}
grupo = []
soma = media = 0.0
while True:
pessoa.clear()
pessoa['nome'] = str(input('Nome: ')).capitalize()
while True:
pessoa['sexo'] = str(input('Sexo [M/F]: ')).uppe... |
from functools import reduce
def run():
my_list = [1,3,4,5,6,7,8,23,44,67,74]
# odd= [ i for i in my_list if i % 2 != 0]
odd = list(filter(lambda x : x%2 != 0, my_list)) # Funcion de orden superiro
#Recive dos parametros = Funcion and interable(Cualquer elemento que logre recorrerce)
... |
"""
3.3 Write a program to prompt for a score between 0.0 and 1.0. If
the score is out of range, print an error. If the score is between 0.0
and 1.0, print a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
If the user enters a value out of range, print a suitable error message... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
圣诞老人的礼物:
圣诞节来临了, 在城市A中圣诞老人准备分发糖果,现在有多箱不同的糖果
• 每箱糖果有自己的价值和重量
• 每箱糖果都可以拆分成任意散装组合带走
圣诞老人的驯鹿最多只能承受一定重量的糖果, 请问圣诞老人最多能带走 多大价值 的糖果
"""
class Solution(object):
def santa_gifts(self, W, boxes):
"""
:type W: int
:type boxes: List[tuple]
:rt... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
寻路问题:
N个城市,编号1到N。城市间有R条单向道路。每条道路连接两个城市,有长度和过路费两个属性。
Bob只有K块钱,他想从城市1走到城市N。问最短共需要走多长的路。如果到不了N,输出-1
优化:
1) 如果当前已经找到的最优路径长度为L ,那么在继续搜索的过程中,总长度已经大于L的走法,就可以直接放弃。
2) 用midL[k][m] 表示:走到城市k时总过路费为m的条件下,最优路径的长度。若在后续的搜索中,再次走到k时,
如果总路费恰好为m,且此时的路径长度已经超过midL[k][m],则不必再走下去了。
"""
... |
import os
import re
filename = os.path.join( "paragraph_2.txt")
# opening the text file and reading it
with open(filename, 'r') as file:
file_contents = file.read()
# finding the special character in the paragraph
p = re.compile('["?","!","(",")","=",">","+","."]')
# finding the letter/ chara... |
#!/usr/bin/env python3
from file_io import file_reader
from file_io import csv_writer
import sys
# Input and output file names
InFile = "examples/wikipedia.csv"
# InFile = sys.argv[1]
InFileName = InFile.split('\\').pop().split('/').pop().rsplit('.', 1)[0]
Data = file_reader.FileReader(InFile)
AllData = ... |
# Генерация целых чисел
def gen_prime(x):
multiples = []
results = []
for i in range(2, x+1):
if i not in multiples:
results.append(i)
for j in range(i*i, x+1, i):
multiples.append(j)
return results
import timeit
# Засекаем время
start_time = timeit... |
from random import randint
import timeit
import copy
import random
def quickselect_median(arr, pivot_fn=random.choice):
if len(arr) % 2 == 1:
return quickselect(arr, len(arr) / 2, pivot_fn)
else:
return 0.5 * (quickselect(arr, len(arr) / 2 - 1, pivot_fn) +
quickselect(arr,... |
"""
Для шифрования строк предназначен модуль hashlib.
"""
import hashlib
'''
рара
рар
ра
р
а
ар
ара
'''
'''
Сохраняем хэши всех подстрок в множество.
Экономия на размере хранимых данных (для длинных строк) и
скорость доступа вместе с уникальностью элементов,
которые даёт множество, сделают решение коротким и эффект... |
from collections import defaultdict
COUNT_ORG = int(input('Введите количество предприятий для расчета прибыли: '))
COUNTER = COUNT_ORG
ORGANISATION = defaultdict(list)
while COUNTER > 0:
NAME_ORG = input('Введите название предприятия: ')
PROFIT_ORG = input('через пробел введите прибыль данного '
... |
from tkinter import *
#set the settings of the window
window=Tk()
window.geometry('310x360') #set size
window.title('Calculator') #set title
window.config(background='coral') #set background
def quit() :
window.destroy()
exit()
#adding the exit buttom
exit=Button(window ,padx=78,pady=14,bd=4,bg="white",comma... |
import turtle
turtle.setworldcoordinates(-600, -500, 600, 500)
turtle.speed(0)
for i in range(200):
turtle.left(90)
turtle.forward(i * 2)
turtle.exitonclick()
|
# read in data
def readInput(filename):
rawData = open(filename, "r").read().split("\n")
data = []
for value in rawData:
data.append(int(value))
return data
# Part 1
def solution_part1(data):
previous = {}
values = [-1, -1]
for value in data:
previous[2020 - value] = v... |
input_quote = input("Enter a 1 sentence quote, non - alpha seperate words: ")
word = ""
for character in input_quote:
if character.isalpha():
word += character
else:
if word and word[0].lower() >= "h":
print("\n", word.upper())
word = ""
else:
word ... |
a =input('Enter the number :')
if int(a)%2==0:
print("even number")
elif int(a)%2!=0:
print('odd number')
else:
print('invalid input')
|
a=str(input("enter the word you want to append \n"))
b= ''
print(b + a)
|
a=int(input("Enter the size of array"))
count=[]
for i in range (0,a):
b=int(input("Enter the element:"))
count.append(b)
count.sort()
print(count)
|
a=int(input("Enter the number:"))
if a>=0:
for i in range (1,6):
print ("The number is :", i*a)
else:
print("Enter a positive number")
|
a = int (input('Enter the number you want to factorise'))
import math
print(math.factorial(a))
|
A = [int(x) for x in input("Enter elements: ").split(" ")]
# A.sort()
x = int(input("Enter no. to search: "))
def binarySearch(A, x, f, l):
mid = (f + l)//2
if l == f:
if A[mid] == x:
return mid
else:
return -1
else:
if A[mid] == x:
return mid
elif x < A[mid]:
return binarySearch(A, x, f, mid ... |
# nest_data_structures
crazy_landl_1 = {
'name': 'Boris',
'phone': '072423423',
'address_of_rent': 'Chelsea',
'age': 55
}
crazy_landl_2 = {
'name': 'Filipe',
'phone': '0646343434',
'address_of_rent': 'Comporta, Portugal',
'age': 28
}
nested_dictionary = {'boris': crazy_landl_1,
... |
# Dictionaries
# Work with key and value paird
# Work like a real dictionary, you just lookup the information for the specific key
# The big difference with list is they are organised with index and here we use keys
# We just make a list of cringe_landlords, but we need more information like their phone numbers and ad... |
# GETTING A NAME
def getting_name():
name = str(input("Name: "))
return name
def name_lenght(name):
tam = 0
for i in range(len(name)):
if name[i] != (""):
tam += 1
print(tam)
def main():
name = getting_name()
name_lenght(name)
main() |
"""
problem formalization:
you are given a list of strings. we say that 2 strings can be chained if the last letter of one of them is the first
letter of the next one ('hola', 'angle' -> 'holangle'). Check if the list of strings (in any order) can be chained in
a circle (every string can be chained to the next one, an... |
"""
problem formalization:
you want to put an advertisement poster over a block of buildings. the block is made of several buildings with different
heights. you can use as many (consecutive) building as you would like, as long as the height of the poster doesn't
exceed the height of the buildings. find the largest pos... |
"""
problem formalization:
you are trying to reach target from source, using some road system represented as directed graph. every road in this
system has a toll that has to be paid for using it. The company in charge of the toll values is now giving a special
discount - "for every trip on our roads, you get a discoun... |
"""
problem formalization:
In some sports league, teams are divided into divisions. Within each division, each team faces each rival several times.
At the end on the season, the top team in each division (the team with the highest amount of wins) proceeds to the
playoffs.
We are now sometime into the season, and you a... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next: return head
pre_node = ListNod... |
"""
验证给定的字符串是否为数字。
例如:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
说明: 我们有意将问题陈述地比较模糊。在实现代码之前,你应当事先思考所有可能的情况。
"""
class Solution:
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
sign_index = 0
exp_index = 0
dot_index = 0... |
# Definition for singly-linked list.
"""
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: ... |
# -*- coding:utf-8 -*-
"""
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
"""
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 0 or len(nums) == 1: return True
i = 0
max_len = 0
... |
from board import *
from tile import *
BOARD_SIZE = 5
def tile_value(player: Player, enemy_player: Player):
"""
The tiles in the middle have a higher value than those closer to edges.
"""
score = 0
tile_values = [[0, 1, 1, 1, 0],
[1, 2, 2, 2, 1],
... |
def show_menu():
print('1.Citire date')
print('2.Cea mai lunga subsecventa cu prorpietatea ca toate numerele sunt pare')
print('3.Cea mai lunga subsecventa cu prorpietatea ca toate numerele au acelasi numar de divizori')
print ('4.Cea mai lunga subsecventa cu proprietatea ca toate numerele sunt prime')
... |
import sys
import commands
#get this of files that end with _pcm.csv
files = commands.getoutput("ls *.pcm.csv").split('\n')
if ("No such" in files[0]) or ("encontrado" in files[0]):
print "PANIC! I cannot find pcm.csv files!!!"
exit()
#get argument
time = float(sys.argv[1])
#open csv to write output
csv = open("pa... |
#Problem 1725. Number Of Rectangles That Can Form The Largest Square
'''
You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi.
You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have... |
#Leetcode 767. Reorganize String
'''
Problem statement:
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:
Input: S = "aab"
Output: "aba"
Exa... |
#1769. Minimum Number of Operations to Move All Balls to Each Box
'''
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.
In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if ... |
#Problem 1217. Minimum Cost to Move Chips to The Same Position
'''
We have n chips, where the position of the ith chip is position[i].
We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:
position[i] + 2 or position[i] - 2 with cost = 0.
po... |
# 1. Factorial ****************************************************************************************
number = 6
product = 1
current = 1
while current <= number:
product *= current
current += 1
print(product)
# Solution:
while current <= number:
# multiply the product so far by the current number
p... |
"""
Week 4 - Video 3 - Writing Files
"""
# to write in a file you first have to open it
# with the mode set for "write"...
openfile = open("some_file.txt", "wt")
"""
Modes for Writing
-------------------------------
w - write (erases the file first)
a - write (appends to the end of the file)
t - text (default)
b - b... |
"""
Course 3
Week 4 - Video 1 - Sorting
"""
# learn to use sorting routines that can be found
# in Python's library
import random
def double_space():
print('', '\n', '')
double_space()
print('normal list:')
data = list(range(1, 11))
print(data)
double_space()
random.shuffle(data) # randomly shuffles given ... |
"""
Some more lesson examples for object oriented programming
"""
# INHERITANCE
class Animal():
def __init__(self):
print("Animal Created!")
def whoami(self):
print("Animal")
def eat(self):
print("Eating...")
class Dog(Animal):
def __init__(self):
# Animal.__init__(... |
"""
Week 2 - Video 1 - Lists
"""
# lists are created using []
empty = []
print(empty)
numbers = [1, 2, 3, 4, 5, 6]
print(numbers)
letters = ['a', 'b', 'c', 'd', 'e']
print(letters)
languages = ['python', 'javascript', 'c++', 'haskell', 'lisp']
print(languages)
# python allows you to mix types in a list,
# but you ... |
"""
Week 1 - Reading 1 - Formatting Strings
"""
print('')
# we can use the format function to add things into a string
first_name = 'Billy'
last_name = 'Joe'
print('My name is {} {}'.format(first_name, last_name))
print('')
# we can further make use of the format function to insert text out of order
# however, we ... |
"""
Split strings such as emails using re
"""
import re
split_term = '@'
email = 'hello@world.com'
match = re.split(split_term, email)
print(match)
# alternative one liner
split_mail = 'johnbravo@cartoon.com'.split('@')
print(split_mail)
# find all instances!!
teacup = 'i\'m a little teacup, short and stout. here... |
"""
Course 3
Week 1 - Reading 1 - Examples
"""
def space():
print('')
contact_list = {
'John Doe': '1-101-233-4567',
'Abe Froman': '1-800-728-7243',
'Betty Bean Ross': '1-888-123-4567'
}
print(
"""
\rLOOKUP A KEY
\r------------
"""
)
def lookup(contacts, name):
"""
Lookup ... |
class Car(object):
def __init__(self, name, price, speed, fuel, mileage):
# creates new instance and defines all arguments except tax
self.name = name
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
# define tax requirements
... |
import random
"""Create a class called Car. In the__init__(), allow the user to specify the
following attributes: price, speed, fuel, mileage. If the price is greater than
10,000, set the tax to be 15%. Otherwise, set the tax to be 12%.
Create five different instances of the class Car. In the class have a metho... |
# parent class
class Animal(object):
def __init__(self, name):
self.name = name
self.health = 100
def walk(self, w=1):
self.health -= 1 * w
return self
def run(self, r=1):
self.health -= 5 * r
return self
def displayHealth(self):
print "\n{}'s c... |
a = input("Enter the string : ")
l = list(a)
l.reverse()
l = "".join(l)
if l==a:
print("Palindrome")
else:
print("Nott palindrome") |
class person:
def __init__(self,name):
self.name = name
def dis(self):
print("Name : %s"%(self.name))
class teacher(person):
def __init__(self,name,exp):
super().__init__(name)
self.exp = exp
def display(self):
self.dis()
print("exp : %s"%(self.ex... |
def avg(a,b):
return (a+b)/2
a,b = input("Enter two numbers : ").split(" ")
a,b = float(a),float(b)
print("Avg of %d & %d is %.f"%(a,b,avg(a,b))) |
print('''
3-Capitalize it
(48 Lines)
Many people do not use capital letters correctly, especially when typing on small devices like smart phones.
In this exercise, you will write a function that capitalizes the appropriate characters in a string. A lowercase
“i” should be replaced with an uppercase “I” if it is both pr... |
import random
Actual = random.randrange(1,100)
Guess = 0
while(Actual != Guess):
x = abs(Actual - Guess)
Guess = int(input())
if Guess < 0 or Guess > 100 :
print ("OUT OF RANGE")
elif Actual==Guess:
print("you make it")
break
elif abs(Actual - Guess) < x :
print(' you... |
import time
from bstclass import BSTNode
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = [] # Return the list of duplicates... |
from src.base.solution import Solution
from src.tests.part1.q207_test_course_schedule import CourseScheduleTestCases
"""
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a ... |
import sys
from src.base.solution import Solution
from src.tests.part1.q209_test_min_size_sub_sum import MinSizeSubSumTestCases
"""
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ? s. If there isn't one, return 0 instead.
For example,... |
import sys
def get_max(lst):
# Don't use the max function
max_val = -sys.maxint
for val in lst:
if val > max_val: max_val = val
return max_val
def get_median(lst):
lst.sort()
n = len(lst)
print(lst)
if n % 2 == 0:
return (lst[n/2-1] + lst[n/2]) / 2.0
else:
... |
from src.structures.treenode import TreeNode
import math
def to_complete_binary_tree(lst):
"""
Complete Binary Tree
:param lst: a list of tree nodes
:return:
"""
n = len(lst)
if n < 1: return None
tree = [TreeNode(lst[0])]
for i in xrange(1,n):
pidx = int(math.floor((i-1) ... |
from src.base.solution import Solution
from src.tests.part1.q151_test_reverse_words import ReverseWordsTestCases
"""
https://leetcode.com/problems/reverse-words-in-a-string/#/description
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Upda... |
from src.base.solution import Solution
from src.tests.part1.q139_test_word_break import WordBreakTestCases
"""
https://leetcode.com/problems/word-break/#/description
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated seque... |
class ColumnDataType(object):
"""
Superclass for defining a data type of a column
"""
def __init__(self, postgres_name):
self.postgres_name = postgres_name
class IntegerColumn(ColumnDataType):
def __init__(self):
ColumnDataType.__init__(self, postgres_name='INT')
class TextColum... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.