text stringlengths 37 1.41M |
|---|
class BucketList(object):
# Defining static variables
bucket_list = dict()
goal_status = ['Active', 'Completed']
category_list = [
'Nature', 'Health', 'Fashion', 'Food', 'Travel', 'Business', 'Education', 'Family',
]
# Initializing class instance variables
def __init__(self):
... |
from Algorithm import Algorithm
class Flowchart:
def __init__(self):
self.ListAlgorithms = []
def setAlghoritm(self, id, name):
if (self.algExist(id)):
print("An algorithm with ID = " + str(id) + " exists, id changed ID = " + str(id + 1) + ';')
self.setAlghoritm(id + 1,... |
#Ussless facts by PFK
name = input("Привет, как тебя зовут?: ")
age = int(input("\nСколько Вам лет?: "))
weight = int(input("\nСколько Вы весите?: "))
print("Если бы трамвайный хам писал Вам в чате, \
он бы обратился так: " , name.lower())
print("А после небольшого спора так: ", name.upper())
fiveTimes = name * 5
pri... |
#chapter 10 - simple GUI
from tkinter import *
#creation and starting window
root_window = Tk()
root_window.title("Окошко в кокошнике:)")
root_window.geometry("444x333")
#creationg frame and objects
main_frame = Frame(root_window)
main_frame.grid() #менеджер размещения, без него не выводится на экран
btn1 = Button(main... |
#Dependencies
import os
import csv
# Create the path name toa ccess the bank data in a csv file
with open('PyBank_Resources_budget_data.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
for row in csvreader:
row num = row_num +1
Date = []
Profit = []
row_num = 0
total month = row_n... |
# -*- coding: utf-8 -*-
"""
K Nearest Neighbor Classification
---------------------------------
This function is built especially for a learned metric
parameterized by the matrix A where this function takes
the matrix M such that A = M * M'
"""
# Author: John Collins <johnssocks@gmail.com>
def knn(ytr, Xtr, M, k, Xte... |
"""
Global and local variables:
Variable n is defined as global
"""
n = 3
""" Function func1 uses global variable 'n'
because there is no local variable 'n' """
def func1():
print("In function1 variable n is: ", n)
#In function func2 variable 'n' is redefined as local variable
def func2(): ... |
"""
Writing to a file
Creating a new file and writing into it
"x" - will create a file
f = open("python.txt", "x") # a new empty file is created
"""
# "w" -write mode will create a file if it does not exist
f = open("python.txt", "w")
"""After creating now writing to an
existing file """
# "a" - will... |
"""
Classes and objects
"""
#to create class use keyword class
class val:
a = 10
#to create an object obj for class val and print value of a
obj = val()
print("Value of a is : ",obj.a)
#Class student use __init__() function to assign values for name and regno
#classes have init function which is executed when... |
words = ["one", "two", "three"]
for word in words:
print word
print word + " has " + str(len(word)) + " letters"
|
#To reverse a string
def reversed_string(inputstring):
return inputstring[::-1]
output = reversed_string("hello")
print output
|
#Length of last word
inputstring = raw_input("Enter a string:")
inputstring = inputstring.strip(" ")
split = inputstring.split(" ")
if len(split)==0:
print 0
elif len(split)==1:
print len(split[0])
else:
print len(split[-1])
|
test_dict_1 = {'YEAR':'2010', 'MONTH':'1', 'DAY':'20'}
print(test_dict_1)
print('=================================')
for key, value in test_dict_1.items():
print(key, value)
|
print("[0]*10:", ['']*10)
aaa = list(range(5))
print(("aaa = range(5) :", aaa))
aaa = list(range(5))
print(("aaa = list(range(5)) :", aaa))
aaa.extend(list(range(5, 0, -1)))
print(('aaa.extend(range(5, 0, -1))', aaa))
aaa.append(None)
print(('aaa.append(6):%s'%aaa.append(6)))
print(('aaa after append:%s'%aaa))
print(... |
from __future__ import print_function
import numpy as np
import cv2
import matplotlib.pyplot as plt
# Goal
# To find the different features of contours, like area, perimeter, centroid, bounding box etc
# You will see plenty of functions related to contours.
# http://docs.opencv.org/master/dd/d49/tutorial_py_contour_fe... |
# # Python Version: 3.5
# Creator - GGbits
# Set: 2
# Challenge: 9
# https://cryptopals.com/sets/2/challenges/9
#
# Description:
# A block cipher transforms a fixed-sized block (usually 8 or 16 bytes) of plaintext into ciphertext.
# But we almost never want to transform a single block; we encrypt irregularly-sized mess... |
s=input("enter string,")
s1=input("enter string2")
for i in range(0,len((s)):
if s[i]==s1[i]:
print(s[i])
|
#aleks calderon
#4.23.2019
#list reversal - iterative
wordList = ["Sunday", "Monday", "Tuesday"]
reverseList = wordList[::-1]
print(reverseList)
|
import random
import paramiko
def convert(currency1,currency2,amount):
dollar = 1; euro = 0.91; shekel = 3.43
if currency1 == "1":
currency1 = dollar
elif currency1 == "2":
currency1 = euro
else:
currency1 = shekel
if currency2 == "1":
currency2 = dollar
elif curr... |
import pandas as pd
import numpy as np
########## Specify the name of excel with the data ##########
fileData=pd.read_excel('Sample DataSet.xlsx')
########## Removes last 2 characters ##########
for loop in range(0,fileData['Section'].count()):
temp_String=str(fileData['Section'].iloc[loop])
temp_Str... |
class SquareTwo():
square_list = []
def __init__(self, s2):
self.s2 = s2
self.square_list.append(self)
def calculate_perim(self):
return self.s2 * 4
def __repr__(self):
return "{} by {} by {} by {}".format(self.s2, self.s2, self.s2, self.s2)
sq_four = ... |
num1= [8, 19, 148, 4]
num2= [9, 1, 33, 83]
list3 = []
for i in num1:
for j in num2:
mult = i*j
list3.append(i*j)
print(list3)
num4= [8, 19, 148, 4]
num5= [9, 1, 33, 83]
mult2 = []
for i in num4:
for j in num5:
mult2.append(i*j)
print(mult2)
numbers = [11, 32, 33, 15... |
randomstring = "Camus"
print(randomstring[0])
print(randomstring[1])
print(randomstring[2])
print(randomstring[3])
print(randomstring[4])
questions = "Where now?", "Who now?", "When now?"
edited = "," .join(questions)
print(edited)
correctthis = "aldous Huxley was born in 1894." .capitalize()
print(correctthis)
f... |
# define a function that take list of word as a argument and return list with reverse of every element in the list
def rr(l):
rl=[]
for i in l:
rl.append(i[::-1])
return rl
numbr=["word","tanmay","anuradha","gopal","shyam"]
print(rr(numbr)) |
name=input("enter your name:->")
def add(n,m):
return n+m
def sub(n,m):
return n-m
def multiply(n,m):
return n*m
def divide(n,m):
return n/m
print("welecome to my calculator")
while True:
menu=input("a:add , s:subtraction , m:multiply , d:divide ::--->>> ")
if menu in('a','s','m'... |
number_one=int(input("enter number one"))
number_two=int(input("enter number two"))
number_three=int(input("enter number three"))
total=((number_one + number_two + number_three)/3)
print(total)
|
#99 bottles code
#Written by Dylan Webb on 1.23.17
i = 99
while i > 0:
if i == 1 :
print(i, "bottle of an undefined beverage on the wall")
print(i, "bottle of an undefined beverage")
else :
print(i, "bottles of an undefined beverage on the wall")
print(i, "bottles of an undefine... |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import scipy.io as sio
import random
from sklearn import linear_model
# The data is from Coursera Machine Learning course/week4/ex3data1.mat
# There are 5000 training examples, each is a 20x20 pixels grayscale
# image of digit 0-... |
'''
######################################################################
Author: Srikanth Peetha [@srikanthpeetha262]
About: Implementating Genetic algorithm & Roulette wheel algorithms
######################################################################
'''
import random
from math import exp
import numpy
impor... |
"""Write a python program which will keep adding stream of numbers inputted by User.
The adding stops as soon as user presses q key on the keyboard"""
sum = 0
while True:
userInput = input("Enter the item price or press 'q' to quit: ")
if userInput != 'q':
sum = sum + int(userInput)
print(f"Yo... |
names = ['kole','bajo','zelje','dugi',]
print(names)
popped_name = names.pop()
print(names)
print(popped_name)
zadnji_frend = names.pop(0)
print("zadnji s kim sa se druzio bio je " + zadnji_frend.title() + ".")
names.remove('zelje')
print(names)
|
pizzas = ['bijela', 'slavonska', 'mozzarela',]
for pizza in pizzas:
print(pizza)
print("\n")
for pizza in pizzas:
print("Ja volim " + pizza.title() + " pizzu.")
print("\n")
print("ja volim sve pizze.")
|
#!/usr/bin/env python3
# HW05_ex09_01.py
# Write a program that reads words.txt and prints only the
# words with more than 20 characters (not counting whitespace).
##############################################################################
# Imports
import re
# Body
def read_file():
file_name = input("Please en... |
# Problem 5 Smallest multiple
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def isprime(a):
# bir sayının asal olup olmadığını kontrol eden fonks... |
# Problem 9 Special Pythagorean triplet
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
for i in range(200,500):
... |
# Problem 34 Digit factorials
# 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
# Find the sum of all numbers which are equal to the sum of the factorial of their digits.
# Note: As 1! = 1 and 2! = 2 are not sums they are not included.
def faktoriyel(n):
toplam = 1
for a in range(1, n + 1):... |
count=0
def check(x,y,board):
for i in range(x):
if board[i][y]==1:
#print('Y',board)
return False
for ix in range(8):
for iy in range(8):
if (ix+iy==x+y or ix-iy==x-y)and(board[ix][iy]==1):
#print('X',board)
return False
re... |
class ModelEx1:
def __init__(self, month, num):
self.month = month
self.num = num
class ModelEx1P2:
def __init__(self, model1, media):
self.model1 = model1
self.num = media
class N1:
def bubble_sort(self, lista):
elements = len(lista) - 1
ordenado = False... |
#Reverse Words in String in its own place.
s=raw_input("Enter a String: ")
def reverse_words(s):
reverseWord = " "
list = s.split()
for word in list:
word= word[::-1]
reverseWord = reverseWord + word + " "
print reverseWord.strip()
reverse_words(s)
|
""" 5) Python class named Circle constructed by a radius and two methods
which will compute the area and the perimeter of a circle."""
class Circle():
def __init__(self, r):
self.radius = r
def area(self):
return self.radius**2*3.14
def perimeter(self):... |
# 9) To print out the first n rows of Pascal's triangle
rows=input("Enter Rows of pascal triangle : ")
def pascal_triangle(n):
f = [1]
y = [0]
for x in range(max(n,0)):
print(f)
f=[l+r for l,r in zip(f+y, y+f)]
return n>=1
pascal_triangle(rows)
|
lst = [x for x in range(1,10)]
for each in lst:
if each == 1:
print('1st')
elif each == 2:
print('2nd')
elif each == 3:
print('3rd')
else:
print('%dth' % each) |
import unittest
from employee import Employee
class EmployeeTest(unittest.TestCase):
def setUp(self):
self.em = Employee('Wang', 'Ming', 10000)
def test_give_default_raise(self):
self.em.give_raise()
self.assertEqual(self.em.salary, 15000)
def test_give_custom_raise(self):
... |
favorite_places = {
'Tom': ['Beijing', 'London', 'Paris'],
'Jack': ['GuangZhou', 'Shanghai', 'Tokyo'],
'Sarah': ['NewYork', 'Paris', 'Moscow']
}
for name in favorite_places:
print(name + ':')
for place in favorite_places[name]:
print(place, end=' ')
print('\n') |
dog = {
'type': 'dog',
'master': 'Tom'
}
cat = {
'type': 'cat',
'master': 'Sam'
}
turtle = {
'type': 'turtle',
'master': 'Sarah'
}
pets = [dog, cat, turtle]
for pet in pets:
print('Pet type: ' + pet['type'])
print('Pet\'s master: ' + pet['master'] + '\n') |
class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# reference to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.nex... |
# ------------------------11111111-------------------------
num1, num2, num3= input('Enter three number ').split()
print(f'{(int(num1) + int(num2) + int(num3))/3}')
# ----------------------------2222222222--------------------
name= input('what is your name: ')
print(name[-1::-1])
# --------... |
l1= [1,3,5,7]
l2 = [2,4,6,8]
new_list= []
l = {(1,2),(3,4),(5,6)}
print(list(zip(*l)))
for pair in zip(l1,l2):
new_list.append(max(pair))
print(new_list)
|
# s ={1:1 , 2:4 , 3:9}
# dictionary = {num:num**2 for num in range(1,11)}
# print(dictionary)
# dictionary2 = {f"key value is {num}" : num**2 for num in range(1,11)}
# print(dictionary)
string = 'jitshil'
count = {i:string.count(i) for i in string}
print(count) |
# something more about tuple ,list, str
new = tuple(range(1,11))
print(new)
new1 = list((1,2,3,4,5,6,4))
print(new1)
new2 = str((1,2,3,4,4,5))
print(new2)
print(type(new2))
|
# generate list with range
#pop method
# index method
# function list
number = list(range(1,21))
# print(number)
# num = number.pop()
# print(number)
# print(number.index(2))
# list =[1,2,3,4,5,6,7,8,9,1]
# print(list.index(1, 3, 11))
# def nagetive_list(l):
# nagetive = []
# for i in l... |
user_info = {
'name' : 'jitshil',
'age' : 21,
'fav_movie' : ['coco' , 'moco'],
'fav_singer' : ['arijit','miner'],
}
# ----------------------------------------------------------------
# d = dict.fromkeys(['name','age'], 'pagla')
# # d = dict.fromkeys(range(1,11),'unknown')
# print(d)
# ----... |
# numbers = [1,2,3,4,5,6,7,8,9]
# num=[]
# for i in numbers:
# if i%2 == 0:
# num.append(i)
# print(num)
# num1 = [i for i in numbers if i%2 == 0]
num2 = [i for i in range(1,11) if i%2 == 0]
# print(num1)
print(num2)
odd_num = [i for i in range(1,11) if i%2 != 0]
print(odd_num) |
fruit1 = ['pinaple','mango','apple']
fruit1.sort()
print(fruit1)
fruit2 = ('pinaple','mango','apple')
print(sorted(fruit2))
guiter=[
{'name': 'yamha','price':8000},
{'name': 'singnature','price':6000},
{'name': 'electric','price':22000}
]
print(sorted(guiter, key=lambda item:item.get('pric... |
example = [[1,2,3],[1,2,3],[1,2,3]]
nested = [[i for i in range(1,100)] for j in range(20)]
print(nested)
new_nested = []
for i in range(1,4):
new_nested.append([1,2,3])
print(new_nested) |
class Animal:
def __init__(self):
pass
def make_a_sound(self, species):
if species == "cat":
print("meow")
elif species == "dog":
print("woof, woof")
elif species == "fox":
print("timtirimtim")
else:
print("Don't know that... |
from datetime import datetime
#get nth letter of a string, 0 based
#output: L
print "HELLO"[3]
#return length of a string
parrot = "Norwegian Blue"
print len(parrot)
#Lower & upper case
print "HELLO".lower()
print "hello".upper()
#String conversion
pi = 3.14
print str(pi)
#check for alpha
#output: true
print "FEFR... |
#merging list tuples with zip
first = ['ben', 'daniel', 'bob']
last = ['hanks', 'swift', 'pitt']
names = zip(first, last)
#will look something like
#[('ben', 'hanks'), ('daniel', 'swift'), ('bob', 'pitt')]
for a, b in names:
print (a, b)
|
"""
A basic example of controlling a motor via smbus
"""
import smbus2
BUS = smbus2.SMBus(1)
ADDRESS = 0x04
MODE_FLOAT = 0
MODE_BRAKE = 1
MODE_FWD = 2
MODE_BKW = 3
def set_motor(motor_id: int, speed: int) -> None:
"""Sets a motor to spin. Any positive value is forwards, any negative one is
backwards.
... |
import random
k = 0
for x in range(0,8):
num = random.randint(1,2)
num3 = random.randint(1,9)
num2 = str(0.1) + str(num) + str(num3)
content = float(num2)
print(content)
k +=content
print(k) |
import random
alphabets= """abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'"""
def encrypt(message):
global shift_generator
encrypted=[]
embeded=[]
for shift in message:
shift_generator = random.randint(1, 26)
print("Shift: ", shift_generator)
if shift in alph... |
n = 42
f = 7.03
s = "cheese"
print("The value of n is {}, f is {} and s is {}".format(n, f, s)) # format passes postional args
print("s = {2}, n is {0} and f is {1}".format(n, f, s)) # using the postional args
# or use a dictionary
d = {"n": 21, "f": 14.06, "s":"mac"}
print("Using dict, n={0[n]}, f={0[f]} ... |
# here we declare reusable functions in our module
# e.g. take a bunch of numbers and return the sum
def addStuff (*args):
#print(args)
total = 0
for num in args:
if type(num) == int or type(num) == float:
total += num
#print(total)
return total
if __name__ == "__... |
# more accurate time capabilities are avl using timeit
# timeit ignores non-python time delays, ie only counts time taken by python to execute code
import random
import time
import timeit
# a function to decorate a function we need to accurately time
def timethis(func):
def func_timer(*args, **kwargs):
... |
from threading import Thread
import time
import random
import sys
# create a runnable class which inherits from Thread class
class MyThreadClass(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
#override the run method of Thread class
def run(self):
... |
# imports go at the top
# define functions here
def document_it(func):
def new_func(*args, **kwargs):
# here is the code to document any function we might want to know about
print("The running function is called", func.__name__)
print("The docstring is", func.__doc__)
if l... |
# iterators
l = [5, 4, 3, True, (1,), 'hi']
i=0
#print('i is', i)
# for iteration
for item in l: # colon indicates starts of a code block
#print(item) #each line of the code block is indented
#print(type(item))
i = i+1
#print('i is', i)
# code block ends when indentation ends
# range o... |
# we can always check the data type
s = 'almost done'
print(type(s))
num = 3.2
print(type(num))
if isinstance(s, str):
print(s, ' is a string')
if isinstance(num, (int, float)): # check data type against a tuple of possibilities
print(num, ' is a number') |
from swapi import Swapi
class SwapiPlanets (Swapi):
def __init__(self, cat, name, climate, terrain, pop):
super().__init__(cat, name)
self.climate = climate
self.terrain = terrain
self.pop = pop
@property
def climate(self):
return self.__climate
... |
# class and methods for extending weather data when it is windy or rainy
from weather import Weather
class WeatherExtended(Weather):
def __init__(self, temp, desc, moreInfo):
super().__init__(temp, desc)
self.moreInfo = moreInfo
def __str__(self):
prn = super().__str__()... |
"""
Write a new top-level module which asks the user for a 'project title', a 'number range (min/max)' and a 'mathematical technique (sum, mean, squares)'
Import the 'sanitize' module and use it to make sure the 'project title' is a title-case string
Also ensure the min and max values are cast as integers and th... |
# ask user to input n and print sqrt from 1 to n
# ask user to input n and check if it is a square
# use show_args to decorate each method
from my_helper import my_helper
def getAllSqrt(n):
sqrtList = list(map(my_helper.getSqrt, range(1,n)))
print (sqrtList)
if __name__ == '__main__':
num = in... |
# Scope - What variables do I have access to?
# Scope Rules
# 1 - Start with local
# 2 - Parent local?
# 3 - Global
# 4 - built-in python functions
# nonlocal keyword
def outer():
x = "local"
def inner():
# nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
... |
# Inheritance
class User():
def __init__(self, email):
self.email = email
def sign_in(self):
print('Logged in')
class Wizard(User):
def __init__(self, name, power, email):
# User.__init__(self, email)
super().__init__(email)
self.name = name
s... |
print('Aswin Barath')
name = input('What is your name? Your Answer:')
print(name)
print('Helllloooo ' + name)
|
import sys
import random
beg = int(sys.argv[1])
end = int(sys.argv[2])
number = random.randint(beg, end)
while True:
try:
guess = int(input(f'Enter a number b/w {beg} & {end}:'))
if beg <= guess <= end:
if number > guess:
print(f'Oh no, {guess} is lesser than th... |
# Dictionary (in other langs, also called hashtables, maps, objects)
dictionary = {
'a': [1, 2, 3],
'b': 'hello',
'x': True
}
# dictionary is an unordered key value pair DataStrucure
print(dictionary['b'])
print(dictionary)
my_list = [
{
'a': [1, 2, 3],
'b': 'hello',
... |
#симулятор телевизора(почти)
class Zombiebox(object):
"""Виртуальный телевизор"""
def __init__(self, channel=0 , volume=0 ):
self.volume = volume
self.channel = channel
def channels(self, choice_to_watch = None):
try:
self.channel = ["Вечно не работающий кана... |
from math import floor, sqrt
# Beatty's sequence with sqrt(2)
# General form would be for n wanted instances
# sum of floor(sqrt(2)*k) for k to n
# Even more general
# S(a, n) where a is the irrational and n is the amount of inputs
# S(a,n) = summation k=1 to n floor(a*k)
# https://mathworld.wolfram.com/BeattySequenc... |
import obtain_symbols
import finlib
import backtesters
import pandas as pd
import sys
import os
from pandas_datareader import data
class SymbolsHelper:
"""
A class that holds important information for calculating misc. commands,
or that holds information so that it doesn't need to be redownloaded and
... |
def seats(data):
for line in data:
row_min = 0
row_max = 128
col_min = 0
col_max = 8
for c in line:
if c == "F":
row_max -= (row_max - row_min) // 2
elif c == "B":
row_min += (row_max - row_min) // 2
elif c =... |
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
# Base conditions
if haystack is None or needle is None:
return -1
# Special case
if haystack == needle:
... |
v = 25
u = 0
t = 10
a = (v-u)/t
print("We have,\n\t v = u + at")
print("or, {0} = {1} + a{2}".format(v, u, t))
print("or, a = ({0}-{1})/{2}".format(v, u, t))
print("hence, a = {0}".format(a))
|
import numpy as np
def get_gradient(data, m_slope, b_intercept, learning_rate):
slope_sum = 0
intercept_sum = 0
len_data = float(len(data))
for i in range(len(data)):
slope_sum += (-data[i][0]) * (data[i][1] - (m_slope * data[i][0] + b_intercept)) * (2/len_data)
intercept_sum += (data[i... |
import sys
int = int(sys.argv[1])
if int % 2 == 0:
print "even"
else:
print "odd"
if int < 50 and int > 0:
print "Minor"
elif int >= 50 and int < 1000:
print "Major"
else:
print "Severe"
|
def fibo(n: int) -> int:
if n <= 1:
return 1
if n == 2:
return 1
return fibo(n - 1) + fibo(n - 2)
num = int(input("Enter number of fibonacci to print "))
for i in range(1, num + 1):
print(fibo(i))
|
#!/usr/bin/env python3
import sys
#print(sys.argv)
try:
salary = int(sys.argv[1])
except:
print("Parameter Error")
exit()
if salary<3500:
salary_need = 0
else:
salary_need = salary-3500
if salary_need<=1500:
salary_push = salary_need*0.03
elif 1500<salary_need<=4500:
salary_push = salary... |
#!/usr/bin/env python3
import sys
#print(sys.argv)
def salary_calculate(salary_raw):
salary = salary_raw*(1-0.165)
if salary<3500:
salary_need = 0
else:
salary_need = salary-3500
if salary_need<=1500:
salary_push = salary_need*0.03
elif 1500<salary_need<=4500:
sala... |
# This is a library of regression model implementations.
import numpy as np
# Ridge regression - i.e. L2 regularised linear regression
# X_ are features, y are targets. Both should be numpy arrays.
# C is the regularisation constant.
# If X_ already contains a bias column (a column of 1s) you can set add_bias to Fals... |
class Contact:
def __init__(self, name, surename, phone, favorite=False, *args, **kwargs):
self.name = name
self.surename = surename
self.phone = phone
self.favorite = favorite
self.args = args
self.kwargs = kwargs
def __str__(self):
if self.favorite is T... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @date: 2017/9/14 9:03
# @name: K-MeansPractice
# @author:vickey-wu
# practice of K-Means algorithm
import pandas as pd
from sklearn.cluster import KMeans
input_flie = "E:/pythonProcess/chapter5/demo/data/consumption_data.xls"
output_file = "E:/pythonProcess/chapter5/demo... |
import sys
import datetime
import time
import logging
import postgres_db
import twitter
# The limits on how many tweets back we can go are not well documented. It appears
# that we can never get more than 200. So might as well ask for more.
NUMBER_OF_TWEETS_TO_REQUEST = 300
# This fetches recent tweets and persist... |
# Na sequência de fibonacci é dado 0 e 1 como primeiros termos da sequência
# e todos os demais termos são calculados em base destes primeiros, somando
# os termos anteriores
def fibonacci(termo):
if termo == 0:
return 0
if termo == 1:
return 1
return fibonacci(termo - 1) + fibonacci(termo... |
# Neste exercício você deve criar um programa que abra o arquivo
# "alunos.csv" e imprima o conteúdo do arquivo linha a linha.
# Note que esse é o primeiro exercício de uma sequência, então o
# seu código pode ser reaproveitado nos exercícios seguintes.
# Dito isso, a recomendação é usar a biblioteca CSV para ler o
# ... |
# contador = 0
# while contador < 100:
# print(contador)
# contador = contador + 1
for contadorFor in range(100):
print(contadorFor)
|
numero1 = int(input('Entre com um número: '))
numero2 = int(input('Entre com um número: '))
numero3 = int(input('Entre com um número: '))
numero4 = int(input('Entre com um número: '))
media = (numero1 + numero2 + numero3 + numero4)/4
print(media)
|
# Quero fazer um programa que torne a primeira letra de cada nome
# do meu usuário em maiscúla
# frutas = 'morango; uva; banana; pêra'
# lista_com_frutas = frutas.split('; ')
# print(lista_com_frutas)
nome = 'fulano siLVa DE SouSA'
nome_correto = ''
# Método split está disponível em strings e fornece uma lista com o
... |
class Pessoa:
def __init__(self, nome, idade, altura):
self.nome = nome
self.idade = idade
self.altura = altura
self.permissoes = []
def listaPermissoes(self):
if len(self.permissoes) == 0:
print('A pessoa não tem permissões')
class Aluno(Pessoa):
def _... |
# Faça um programa que recebe um número inteiro do
# usuário e imprime na tela a quantidade de divisores
# desse número e quais são eles.
divisor = 1
numero = int(input('Entre com um número: '))
while divisor <= numero/2:
if numero % divisor == 0:
print(divisor)
divisor = divisor + 1
|
ultimo = int(input('Entre com um número: '))
contador = 1
while contador <= ultimo:
print(contador)
contador = contador + 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.