text stringlengths 37 1.41M |
|---|
import csv
def read_from_csv(filename):
with open(filename, 'r') as csv_file:
reader = csv.DictReader(csv_file, dilimetr=';')
data = []
for row in reader:
data.append(row)
return data
filename = 'data.csv'
new_data = read_from_csv(filename)
print(new_data) |
# функции сортировки
# my_list = [12, 3, 45, 23, -10, 1]
# sorted_list = sorted(my_list, reverse=True, key=abs)
# print(sorted_list)
#
# def sort_by_len_and_name(name):
# return len(name), name # сортировка и по длине и по алфавиту
#
# my_str_list = ['Jhon', 'Jack', 'Jacob', 'Max', 'Violeta']
# sorted_my_str_lis... |
# these are you health points and your opponents health points
hp = 100
enemyhp = 100
# this lets your opponet use a move at random
import random
# these are the level 2 water moves if you pick the pokemon totidile
wgun = 40
bubble = 30
# these are the level 2 fire move if you pick the pokemon Cyntiquil
flame_wheel ... |
for x in range(0,14):
print(x)
for x in range(100, 600, 27):
print(x)
for x in range(10, 0, -1):
print(x)
n = int(input("type a number"))
for n in range(n):
print("are we there yet")
second=0
int(second)
for x in range(0,5):
average=int(input("type a numbers"))
second=second+average
int(seco... |
# IMPORT SPARK AND CREATE CONTEXT
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster('local').setAppName('ClassLoadSaveData.py')
sc = SparkContext(conf = conf)
# Import Libraries
import pandas
import os
import operator
# Create a RDD of a text file
Text = sc.textFile('bible.txt')
Tokenize ... |
import sqlite3
def connect(dbname):
conn=sqlite3.connect(dbname)
conn.execute("CREATE TABLE IF NOT EXISTS GSOC(NAME TEXT, DESC TEXT)")
print("Table created successfully")
conn.close()
def insert_into_table(dbname, values):
conn=sqlite3.connect(dbname)
insert_sql="INSERT INTO GSOC (... |
def recurse(s, t, i, j, s1, t1):
# print(i, s[i], j, t[j], s1, t1)
if i == len(s) and j == len(t):
print(''.join(s1))
print(''.join(t1))
print()
return
if i < len(s):
recurse(s, t, i+1, j, s1 + [s[i]], t1 + ['-'])
if j < len(t):
recurse(s, t, i, j+1, s1 + ... |
# 将抓取的列表中的字典的人气值一列按大小重新进行排序
import operator
import re
class OnlineSort():
def online_change(self, num_lists, num_key='online'):
for num_list in num_lists:
list_num = str(num_list[num_key]).replace(',', '')
reg = r'(.+?)万'
matchObj = re.match(reg, list_num)
... |
active = True
print
while active == True:
print('Starting up...')
try:
file_name = input('Which file do you want to scan?')
print("type 'q' to quit. ")
if file_name == 'q':
active = False
break
print('Cleaning up...\nExiting program...\nT... |
def insertion_sort(lst):
"""Given a list, sort in place using insertion sort algorithm.
>>> insertion_sort([6, 5, 3, 1, 8, 7, 2, 4])
[1, 2, 3, 4, 5, 6, 7, 8]
"""
for i in range(1, len(lst)):
j = i
x = lst[i]
while j > 0 and lst[j-1] > x:
lst[j] = lst[j - 1]
... |
"""Sunny and Johnny together have M dollars they want to spend on ice cream.
The parlor offers N flavors, and they want to choose two flavors so that they
end up spending the whole amount."""
def ice_cream_flavors(int_list, money_amt):
"""Given the cost of these flavors, display the indices of the two flavors
... |
"""Cracking the Coding Interview Problem 4.3
Given a binary tree, design an algorithm that creates a linked list of all the
nodes at each depth (e.g. if you have a tree with depth D, you'll have D linked
lists)
Make a binary search tree ...
>>> tree3 = make_bst([1, 2, 3])
>>> tree3.data
2
Make the list of Linked Li... |
from collections import defaultdict
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
addjust_tickets = defaultdict(list)
for from_addr, to_addr in sorted(tickets)[::-1]:
addjust_tickets[from... |
import time
import datetime
start_time = datetime.datetime.now()
five_sec = datetime.timedelta(seconds=1) * 5
print "Start time: %s" % (start_time)
while True:
time.sleep(1)
if datetime.datetime.now() >= start_time + five_sec:
break
print "End time: %s" % (datetime.datetime.now())
|
'''
funcoes para abrir o mapa de um arquivo
exemplo de arquivo:
labirinto
S1100
01100
01F00
custos
12500
02100
01400
'''
def addAround(labirinto):
zeroRoll = (len(labirinto[0]) + 2) * '0'
newLab = []
for e in labirinto:
newLab.append('0' + e + '0')
newLab.insert(0, zeroRoll)
newLab.appe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test how to terminate multiprocessing.
Usage:
./multiprocessing_terminate.py
python multiprocessing_terminate.py
Input Variables:
None.
Reference:
https://pymotw.com/2/multiprocessing/basics.html
Created on 2016 Sep 8 by Edwin Campos
Last modification on 2018 De... |
"""
Using either a reader or a DictReader, load records from 12-serialization/data/people.csv file
Print the following information:
Number of all records
Number of people missing an e-mail address
Number of people with middle name
Save all the records with e-mail missing to a new file
"""
import csv
i... |
import csv
if __name__ == "__main__":
rows = []
with open("12-serialization/data/example.csv") as f:
reader = csv.reader(f)
for row in reader:
rows.append(row)
print(row)
rows.append([6, "Phillis", "Late", "Female", "plate0@loc.gov", "Civil Engineer"])
with open... |
class Animal:
def __init__(self, name):
self._name = name
@property
def name(self):
return f"My name is {self._name}"
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
@property
def name(self):
return f"My name is {self._name}, the dog."
if... |
"""
Write a class `Bakery`, which:
- has a common variable called `storage` (int)
- has a function called `baker()` which (for 10 loops) notes down current
state of the storage, sleeps for 0.1s and adds 1 to the storage, then
sleeps for 1s
- has a function called `customer()` which (for 10 loo... |
"""
1. Create the following functions:
1. `generate_random(out_q, n)` which generates `n` random integers and puts them in `out_q` Queue
2. `square(in_q, out_q, n)` which takes numbers from the `in_q` Queue and puts their squares in the `out_q`.
3. `to_binary(in_q, out_q, n)` takes numbers from the `in_q` ... |
# Implementation of a custom iterator
class ZeroToN:
def __init__(self, n):
self.n = n
def __iter__(self): # called when iterator is created
self.i = -1
return self
def __next__(self): # called on next
self.i += 1
if self.i < self.n:
return self.i
... |
# EXERCISE 1
# Define a class called Bike that accepts a string and a float as input, and assigns those inputs respectively to two instance variables, color and price.
# Assign to the variable testOne an instance of Bike whose color is blue and whose price is 89.99.
# Assign to the variable testTwo an instance of Bike ... |
# | ------------------ |
# | --- TEST CASES --- |
# | ------------------ |
### Assert
def square(x):
return x*x
assert square(3), 9
### try and except
mylist = [1,2]
try:
print(mylist[2]) # IndexError: list index out of range
y = 10 / 0 # ZeroDivisionError: can't divide by 0
e... |
### RANGE
number = list(range(1,11))
print(number)
for i in range(5):
print(i) # 0 1 2 3 4
# | ------------------ |
# | ------- FOR ------ |
# | ------------------ |
for _ in range(3):
print("Hello, Vitor!")
##### Printing a list
myParty = ["Vitor", "Marghie", "Seba", "Giuseppe"]
for name in... |
# follow this tutorial
# http://machinelearningmastery.com/regression-tutorial-keras-deep-learning-library-python/
import numpy
import pandas
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
fro... |
#Import the modules you need.
import os
import csv
#Set Path
csvpath = os.path.join('resources','02-Homework_03-Python_Instructions_Pybank_Resources_Budget_data.csv')
#Define Dictionary
Valuedict = {}
Timedict = {}
#Open CSV File
with open(csvpath, 'r') as csv_file:
csvreader = csv.reader(csv_file, delimiter= ",")
... |
# coding: utf-8
# In[2]:
print(5)
# In[4]:
print("Helloworld")
# In[5]:
a=1
print(a)
# In[8]:
a=b=c=1
a
# In[9]:
a=5
type(a)
# In[11]:
b='sailesh'
type(b)
# In[12]:
c=2.5
type(c)
# In[15]:
a="i'm sailesh"
print(a)
# In[17]:
print('{} is {} {}'.format("ghost","sailesh","germany"))
#... |
from classes import Stations as st
from classes import Route as rt
from classes import Solution as sn
from functions import helper
import random as rd
import numpy as np
import matplotlib.pyplot as plt
def hillclimber(solution, route_iterations = 10000, connection_iterations = 0):
""" Hillclimber algortihm that tr... |
import csv
from numpy import array
class Matrix:
def __init__(self, filename):
self.filename = filename
self.mat = []
reader = csv.reader(file(filename))
header = reader.next()
self.colnames = header[1: ]
self.rownames = []
for line in ... |
#!/usr/bin/env python
# Grant Nelson and John M. Singleton
# CSCI 520 - Distributed Systems
# Project 2 (Consensus Project)
# due Apr 6, 2020 by 11:59 PM
import threading
import time
checkTimeoutTime = 0.01 # in seconds
class customTimer:
# This is a timer which will a method after a specificed amount of time.... |
"""Compute the first 8 fibonacci numbers."""
# initial values at (0,1)
prev = 0
curr = 1
# repeat 8 times
for _ in range(8):
# output the next number
print(curr)
# update the numbers according to fibonacci rule: f(n) = f(n-1) + f(n-2)
# using python's simultaneous assignment notation to allow this
... |
from tkinter import *
root = Tk()
def myclick():
myLabel = Label(root,text = "clicked!")
myLabel.pack()
mybutton = Button(root,text = "try click",command = myclick,padx = 10 , pady =10)
#other parameters state = DISABLED ,fg = "<color>" ,bg = "<color>""
mybutton.pack()
root.mainloop() |
# Script to check the output of the coffeeshop program
#
import sys
import re
from operator import eq
# Helper function
def matchThread(prefix, suffix, line, linenum):
match = re.search(prefix+"(\d+)"+suffix,line)
if (not match == None):
if (not match.groups()[0].isdigit()):
print "Error: bogus output a... |
from stack import Stack
def calculator(input):
dict = {}
dict['^'] = 4
dict['*'] = 3
dict['/'] = 3
dict['+'] = 2
dict['-'] = 2
dict['('] = 1
operand_stack = Stack()
operands_stack = Stack()
equation = list(input.split())
for token in equation:
if token in 'ABC... |
count = 0
sum = 0
n = int(input("please enter a number.: "))
while n > 0:
d = n%10
n = n//10
count += 1
sum += d
print("Number of digits:",count)
print("The sum of digits:",sum)
|
#!/usr/bin/python
'''
n! means n x (n - 1) x ... x 3 x 2 x 1
For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
'''
target = 100
def factorial(number):
if number == 1:
retur... |
#!/usr/bin/python
'''
Project Euler Problem 4
Answer: 906609
'''
def is_palindrome(x):
z = str(x)
l = len(z) / 2
if z[:l] == z[-l:][::-1]:
return True
return False
upper_limit = 999
lower_limit = 100
found = False
palindrome = 0
for x in xrange(upper_limit, lower_limit - 1, -1):
for ... |
#!/usr/bin/python
'''
Project Euler Problem 3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
def factorize(number):
factors = []
factor = 2
while number > 1:
while factor <= number:
if number % factor == 0:
... |
from enum import Enum
class BookAttributes(Enum):
code = 'code'
title = 'title'
author = 'author'
edition_year = 'edition_year'
class Book():
def __init__(self, title, author, edition_year, code):
'''
A book encapsulation
Parameters:
Strings:
title... |
#!/usr/bin/env python3
i,j = 1,1
print("\n----------------------9x9乘法表-------------------------\n")
for i in range(1,10):
for j in range(1,i+1):
print("{}x{}={}\t".format(j,i,i*j),end="")
print()
|
#!/usr/bin/env python3
import sys #导入 sys 模块
list=[1,2,3,4]
it = iter(list) #创建迭代器对象
while True:
try:
print(next(it))
except:
sys.exit()
|
#!/usr/bin/env python3
import sys
def fn(n): #生成器函数
a,b,counter = 0,1,0
while True:
if (counter > n):
return
yield a #遇到yield时,函数会暂停并保存当前所有的运行信息
a,b = b,a+b #返回yield值,并在下一次执行next()方法时从当前位置继续运行
counter += 1
f = fn(10)
while True:
try:
print(next(f)... |
import unittest
from src.shortest_path import ShortestPathCalculator
from src.util_functions import Constants
# This class implements unit test cases for the graph given in assignment
class ShortestPathTestSuite(unittest.TestCase):
calculator = ShortestPathCalculator()
def test_self_path(self):
self... |
class Utils:
PREFIX_URL = "http://"
def isPalindrom(self, word):
try:
word = word.replace(" ","").lower()
bResult = False
size = len(word)-1
if size <= 1:
bResult = True
else:
for index in range(0,size-1):
... |
import numpy as np
import pandas as pd
def sigmoid(z):
'''
Function: sigmoid
Summary: Activation Function used for Logistic Regression and Neural Nets
Attributes:
@param (z): scalar or numpy array of any size.
Returns: outut of 1/(1+np.exp(-z))
'''
return 1 / (1 + np.exp(-z))
de... |
def mean(lst):
return sum(lst) / len(lst)
def std(lst):
mu = mean(lst)
ss = mean([(x - mu)**2 for x in lst])
return pow(ss, 0.5)
def corr(lst1, lst2):
mu1 = mean(lst1)
mu2 = mean(lst2)
sd1 = std(lst1)
sd2 = std(lst2)
cov = mean([x[0]*x[1] for x in zip(lst1, lst2)]) - mu1*mu2
... |
# Project: Fizz Buzz
upper_limit = 101
print("Fizz buzz counting up to {}".format(upper_limit - 1))
for i in range(1,upper_limit):
if i % 3 == 0 and i % 5 == 0:
print("fizz buzz")
elif i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
else:
print(i) |
from abc import ABCMeta, abstractmethod
class Variable(metaclass=ABCMeta):
"""
Used for implementing variables that can be used by different sub processes like the Scheduler.
"""
@abstractmethod
def sample(self):
pass
def reset(self):
pass
class Constant(Variable):
"""
... |
"""
在Python中,属性和方法的访问权限只有两种,也就是公开的和私有的,
如果希望属性是私有的,在给属性命名时可以用两个下划线作为开头
"""
"""
在实际开发中,我们并不建议将属性设置为私有的,因为这会导致子类无法访问(后面会讲到)。
所以大多数Python程序员会遵循一种命名惯例就是让属性名以单下划线开头来表示属性是受保护的,
本类之外的代码在访问这样的属性时应该要保持慎重。这种做法并不是语法上的规则,
单下划线开头的属性和方法外界仍然是可以访问的,所以更多的时候它是一种暗示或隐喻,
关于这一点可以看看我的《Python - 那些年我们踩过的那些坑》文章中的讲解。
"""
class Test:
# pri... |
"""
定义和使用列表
- 用下标访问元素
- 添加元素
- 删除元素
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
# 定义列表
fruits = ['grape', '@pple', 'strawberry', 'waxberry']
print(fruits)
# 通过下标访问元素
print(fruits[0]) # grape
print(fruits[1]) # @pple
print(fruits[-1]) # waxberry
print(fruits[-2]) # st... |
#!/usr/bin/env python
# coding: utf-8
# # Exemplo de ETL Simples
#
# Desenvolvido por: Renato Rossi (renaroscoding@gmail.com) para o Instagram Puro Byte
# A idéia deste exercício é mostrar na prática como funciona um ETL simples para gerar um relatório em formato CSV de quantidade de emprestimos de veículos por regi... |
def readFile():
#print('readFile')
scorelist = []
try:
fileObject = open('.score', 'r')
except:
return []
scoreString = fileObject.read()
#print('hello')
#print(scoreString)
stringList = scoreString.split(';')
#print(stringList)
for s in stringList:
try ... |
import collections
import heapq
import hex_model
af = '\x1b[38;5;{}m'.format
ab = '\x1b[48;5;{}m'.format
clear = '\x1b[0m'
hexagon_colors = {
hex_model.Color.blue: 38,
hex_model.Color.yellow: 214,
hex_model.Color.black: 237,
}
def display_board(board):
"""
Display the board of flat-top hexes.
... |
#Manuela Rafael Onofre de Sousa - RA:202534
#O programa tem como objetivo a criação de uma matriz ixj(que corresponde a NxN, dado o input N) em que, dado um item[i][j], quando i for divisor de j ou vice-versa esse item seja um '*' e quando i não for divisor de j nem vice-versa o item seja um '-'
N=int(input()) #a dimen... |
class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
string = list(s)
def reverse(s, e):
i, j = s, e
while i<j:
string[i], string[j] = string[j], string[i]
i+=1
j-=1
... |
import random
import time
from sys import exit
red = [1, 3, 5, 7, 9, 12,
14, 16, 18, 19, 21, 23,
25, 27, 30, 32, 34, 36]
black = [2, 4, 6, 8, 10, 11,
13, 15, 17, 20, 22, 24,
26, 28, 29, 31, 33, 35]
def playerBet(money):
more = True
bets = []
while more:
rb = raw_input('1.Red\n2.Black\n3.Even\n4.O... |
#### --->below will run: prints hello world
#### FLASK_APP=hello.py flask run
#### add an "about" to http://127.0.0.1:5000/ shows "about me"
#### "ctrl" c --->quits
#### from the Flask website hello world example
from flask import Flask
#### importing Flask object from Flask class passing in name of file hello.py
ap... |
# Definir una lista por asignación que almacene los nombres de los primeros cuatro meses del año. Mostrar el primer y último elemento de la lista.
meses=["Enero", "Febrero", "Marzo", "Abril"]
print("Longitud de la lista:",len(meses))
print(meses[0]) # Se muestra enero
print("********************")
print(meses[3]) # Se... |
# Definir una tupla con tres valores enteros. Convertir el contenido de la tupla a tipo lista.
# Modificar la lista y luego convertir la lista en tupla.
fechatupla1 = (25, 12, 2016)
print("Imprimimos la primer tupla")
print(fechatupla1)
fechalista = list(fechatupla1) # Función list(tupla) convierte la información de ... |
# Almacenar en una lista de 5 elementos tuplas que guarden el nombre de un pais y la cantidad de habitantes.
# Definir tres funciones, en la primera cargar la lista, en la segunda imprimirla y en la tercera mostrar el nombre del país con mayor cantidad de habitantes.
def cargar_paisespoblacion():
paises=[]
for... |
# Permite obtener las claves y valores de un diccionario
diccionario = {"color": "rosa", "marca": "Zara", "talla": "U"}
for clave, valor in diccionario.items():
print(f"El valor de la clave {clave} es {valor}") |
# Retorna True o False
cadena = "bienvenido a mi aplicación".capitalize()
print(cadena.startswith("Bienvenido"))
print(cadena.startswith("aplicación"))
print(cadena.startswith("aplicación", 16)) |
# Crear una lista por asignación. La lista tiene que tener 2 elementos. Cada elemento debe ser una lista de 5 enteros. Calcular y mostrar la suma de cada lista contenida en la lista principal.
lista=[[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [8, 10, 56, 89, 58]]
# Manual:
suma1=lista[0][0]+lista[0][1]+lista[0][2]+lista[0][3]... |
"""Comandos de salida"""
# system.exit()
import sys
age = int(input("Ingrese su edad: "))
if age<18:
sys.exit("Eres menor de edad") # Sale del programa
else:
print("Eres mayor de edad") |
# Programa que cuenta hacia atrás desde cinco y luego dice “¡Despegue!”.
x=5
while x>0:
print(x)
x=x-1
print("¡Despegue!") |
import numpy as np
# 1. Acceso a vectores y sus elementos
A = np.array([2,4,6,8,10])
print("A[0]=", A[0])
print("A[2]=", A[2])
print("A[-1]=", A[-1])
# 2. Acceso a matrices, filas y elementos
A = np.array([[2,4,6,8,10],
[-5,8,9,0],
[-6,7,11,19]])
# Primer elemento de la primera fila
pr... |
# Retorna un entero representando la cantidad de veces que un caracter está en la subcadena
cadena = "bienvenido a mi aplicación".capitalize()
print(cadena.count("a")) |
'''
print("It isn\'t what they said")
s= 'First Line.\nSecond line.' # \n significa crear una nueva línea.
print(s) # Al imprimir, el texto "Second line." aparecerá en la línea siguiente.
'''
print(r'C:\some\name') # la r antes de la cita hace que se cree una cadena de texto sin formato, tomando en cuenta que \n sig... |
# Programa para convertir una temperatura desde grados Fahrenheit a grados Celsius
# De forma normal:
"""fahrenheit = float(input("Introduzca la temperatura en grados Fahrenheit: "))
celsius = (fahrenheit-32) * 5 / 9
print(round(celsius))"""
# Para que no genere errores:
entrada = input("Introduzca la temperatura e... |
'''
该代码参考:《Python自然语言处理实战:核心技术与算法》第3章 规则分词-正向最大匹配
正向最大匹配(Maximum Match, MM)
假定分词词典中的最长词有i个汉字字符,则用目标文本的前i个字符作为一次迭代的临时字符序列,将该序列在字典中匹配
若匹配失败,则缩短临时字符序列,从什么方向缩短呢?从右往左的方向缩短,即去掉临时字符序列的最后一个字符,对剩下的字符序列继续匹配词典
若匹配成功,则将该临时字符序列当作一个词输出
'''
# 正向最大匹配(Maximum Match, MM)
class MM(object):
def __init__(self, dict_path, ... |
from typing import Sequence
add = lambda x, y: x + y
print(add(5, 7))
def double(x):
return x * 2
sequence = [1, 3, 5, 9]
doubled = [double(x) for x in sequence]
doubled = list(map(double, sequence))
print(doubled) |
#to build out classes using other classes
#comp to many things
class BookShelf:
def __init__(self, *books):
self.books = books
def __str__(self):
return f"BookShelf with {len(self.books)} books."
class Book:
def __init__(self, name):
self.name = name
def __str__(self):
... |
# Value that can be either true or false
# Comparisons:
# == (equal/equal)
# != (not equal)
# > (greater than)
# < (less than)
# >= (greater than and equal to)
# <= (less than and equal to)
# Can be used anywhere but have different response
print( 5 == 5)
print(5 > 5)
print(10 != 10)
friends = ... |
# While loop
number = 7
while user_input != "n":
user_input = input("Would you like to play? (Y/n)")
if user_input == "n":
break
user_number = int(input("Guess our number:"))
if user_number == number:
print("You've guessed right!")
elif abs(number - user_number) == 1:
print(... |
def createStack():
stack = []
return stack
def isEmpty(stack):
if(len(stack) == 0):
return True
return False
def push(stack, data):
stack.append(data)
def pop(stack):
if(not(isEmpty(stack))):
stack.pop()
stack = createStack()
push(stack, 5)
push(stack, 5)
push(stack, 5)... |
class Node:
def __init__(self, data):
self.value = data
self.next = None
def traverseLinkedList(l1):
l = l1
while(l.next != l1):
print(l.value)
l = l.next
print(l.value)
def insertAtStart(head, data):
ptr = Node(data)
l = head
while(l.next != l1):
l... |
def linearSearch(data, element):
for ind, ele in enumerate(data):
if ele == element:
return ind
return -1
data = [1, 2, 3, 1, 2, 1, 2, 1, 3, 2, 1, 3, 2, 1, 2, 1, 2, 1, 2, 5, 6, 7, 8, 9, 9, 0, 2]
element = 1
search = linearSearch(data, element)
print("--------------------------------------L... |
import sqlite3
import csv
import json
# proj3_choc.py
# You can change anything in this file you want as long as you pass the tests
# and meet the project requirements! You will need to implement several new
# functions.
# Part 1: Read data from CSV and JSON into a new database called choc.db
DBNAME = 'choc.db'
BARSC... |
""" NLPIA Chapter 2 Section 2.1 Code Listings and Snippets """
import pandas as pd
sentence = "Thomas Jefferson began building Monticello at the age of "\
"twenty-six."
sentence.split()
# ['Thomas', 'Jefferson', 'began', 'building', 'Monticello', 'at', 'the',
# 'age', 'of', 'twenty-six.']
# As you can see, this s... |
# cngram.py
# Using Python 3.4.3
import math
from collections import defaultdict, Counter
class CNGram:
"""Represents a section of text with n characters.
Args:
lang (str): The language of the n-gram model
words (list<str>): Tokenized words for a single language.
num_letters (int):... |
class Account:
def __init__(self, number, holder, balance, limit):
print("Construindo objeto... {}".format(self))
self.__number = number
self.__holder = holder
self.__balance = balance
self.__limit = limit
def statement(self):
print("Saldo de R${} do titular {}.... |
class node:
def __init__(self):
self.data=0
self.next=None
self.prev=None
class bst:
def __init__(self):
self.root=None
def add(self):
self.a=int(input('Enter data:'))
self.new=node()
self.new.data=self.a
if self.root is None:
... |
# import sqlite3
# class Student():
# def __init__(self, first, last, handle, cohort):
# self.first_name = first
# self.last_name = last
# self.slack_handle = handle
# self.cohort = cohort
# student = Student('Bart', 'Simpson', '@bart', 'Cohort 8')
# print(f'{student.first_nam... |
from tree import Tree, Node
from preOrderTraversal import preorder
def even(n):
if n%2 ==0:
return True
return False
def listtobst(t, l):
'''
t = Tree object
l = input list
'''
if not l:
return None
if even(len(l)):
pos = int(len(l)/2)
else:
pos = int((len(l)-1)/2)
v = l[pos]
print(v)
node = ... |
#! /usr/bin/env python3
#John Cordes
#Draws picture of computer monitor
from graphics import *
win = GraphWin("Monitor", 500, 500)
win.setCoords(-10,-10,10,10)
win.setBackground("purple")
oval = Oval(Point(-7,-7), Point(7,-5))
oval.setFill("pink")
oval.draw(win)
rectangle = Rectangle(Point(-1,-5.5), Point(1,-2))
re... |
#!/usr/bin/env python
# -*- coding: UTF-8
import numpy as np
# 归并排序
#### 这是合并的函数, 将序列L[first...mid]与序列L[mid+1...last]进行合并
def mergearray(L,first,mid,last,temp):
#对i,j,k分别进行赋值
i, j, k = first, mid + 1, 0
#当左右两边都有数时进行比较,取较小的数
while (i <= mid) and (j <= last):
if L[i] <= L[j]:
temp[k] = L[i]
... |
class Person:
def __init__(self,n,y):
self.name = n
self.year = y
def whatName(self):
print self.name
p = Person('mark',1994)
p.whatName()
|
#advent of code day 2 part 2 2020
#check passwords that match their policies from file
#new pass policy, 1-3 a: abcde means a must be the
#first number or 3rd number
#debugging lines in triple quotes """
#open data file and process data into usable list
file = open(r"passList", "r")
rawData = file.readlines()
passlis... |
class SchoolMember:
def __init__(self, name, age):
self.name = name
self.age = age
class Teacher(SchoolMember):
def __init__(self, salary):
self.salary = salary
def tell(self, salary):
return self.salary
class Student(SchoolMember):
def __init__ (self,marks):
... |
import shutil
# Первое задание
file = open("kyrgyzstan.txt", "w")
writer = file.write("Kyrgyzstan, country of Central Asia.It is bounded by Kazakhstan on the northwest and north, by China on the east and south, and by Tajikistan and Uzbekistan on the south and west. Most of Kyrgyzstan’s borders run along mountain cres... |
school = {'1a' : 33,'3a' : 29,
'4г' : 31, '5в' : 28,
'9б' : 29, '10в' : 21 , '11a' : 20, }
print(school)
print()
school['5в'] = 26
school['9а'] = 25
print(school)
del school['4г']
print(school)
print(int(sum(school)))
|
sum_of_multiples = 0
for i in range(1, 1000):
if (i % 3) == 0 or (i % 5) == 0:
sum_of_multiples += i
print( sum_of_multiples)
|
#===========
#Hello World
#===========
print("Hello, World!")
#===============
#Python Comments
#===============
#This is a sinle-line comment
#===========================
#Python Multi-lines Comments
#===========================
#This is a long comment
#and it extends
#to multiple lines
"""This is also a
perfect... |
'''
Created on Apr 2, 2018
@author: Sumeet Agrawal
'''
hrs = input("Enter Hours:")
h = float(hrs)
rateperhour = input("Enter Rate Per Hour:")
r = float(rateperhour)
if(h < 40):
totalpay = h * r
else:
totalpay = (40 * r) + (1.5 * (h-40) * r)
print(totalpay) |
def curva(n):
if n == 0: #Si no hay elementos nregresa una lista vavia
return []
else:
c = curva(n - 1) #Cadena de la curva del Dragon
r = c[::-1] #Cadena reversa de la curva
i = ['L' if g == 'R' else 'R' for g in r] # Cadena de r, que hace los giros, y convierte cada L en R y ... |
#! python3
# osWalk.py - Learning how to walk a directory tree
import os
for folderName, subFolders, fileNames in os.walk('S:\\Documents\\GitHub\\ATBS'):
print('The current folder is ' + folderName)
for subFolder in subFolders:
print('SUBFOLER OF ' + folderName + ': ' + subFolder)
for fileName in... |
print('Hello World')
# Good job :)
# Hey there =)
# The round function rounds to the nearest int
print(round(6.8))
print(round(6.3)) |
print('Typing 1 prints Hello')
print('Typing 2 prints Howdy')
print('Anything else prints Greetings!')
print()
print('Type something')
spam = input()
if spam == '1':
print('Hello')
elif spam == '2':
print('Howdy')
else:
print('Greetings!') |
#! python3
# regexFindAll.py - Understanding how the findall() function works
# Import re
import re
# String for search() and findall() functions to use
myNumbers = 'Cell: 415-555-9999 Work: 212-555-0000'
# Create the regex format
phoneNumRegex = re.compile(r'\d{3}-\d{3}-\d{4}')
# Using search() only brings up the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.