text
stringlengths
37
1.41M
dictionary={} dictionaryFile=open('birthday.txt','a') dictionaryFile.close() dictionaryFile=open('birthday.txt','r') for line in dictionaryFile: #if ',' in line: # dictionary[line[:line.index(',')]]=line[line.index(',')+1:].strip() data=line.strip().split(',') dictionary[data[0]]=data[1] dictionaryFile.close() ch...
from random import shuffle def max_min(lst): """ Função que me retorana min e max de uma lista calcular o valor max e min da lista Calculate the maximum and minimum of a list lst falar tb do tempo de execução se constante, linear... :param lst: list :return: tuple:(max, min) """ if...
class Pessoa(object): def __init__(self, nome, nascimento): self.nome = nome self.nascimento = nascimento def idade(self, hoje): hd, hm, ha = hoje nd, nm, na = self.nascimento x = ha - na return x if __name__ == "__main__": fante = Pessoa('John Fante'...
def isLucky(n): n_string = str(n) n_list = [] is_zero = 0 for digit in n_string: n_list.append(int(digit)) half = len(n_list)/2 for item in range(0, len(n_list)): if item < half: is_zero += n_list[item] else: is_zero -= n_list[item] return...
def reverseParentheses(s): string_array = list(s) while "(" in string_array: inner_open = 0 inner_close = 0 for item in range(0, len(string_array)): if string_array[item] == "(": inner_open = item elif string_array[item] == ")": ...
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight): if yourLeft == friendsLeft: return yourRight == friendsRight elif yourRight == friendsLeft: return yourLeft == friendsRight else: return False if __name__ == '__main__': print areEquallyStrong(10, 15, 5, 20)
""" A string is said to be beautiful if b occurs in it no more times than a; c occurs in it no more times than b; etc. Given a string, check whether it is beautiful. Example For inputString = "bbbaacdafe", the output should be isBeautifulString(inputString) = true; For inputString = "aabbb", the output should be isB...
def palindromeRearranging(inputString): input_array = list(inputString) once = False checked_letters = [] for letter in input_array: if letter in checked_letters: continue if inputString.count(letter) % 2 == 1: if once: return False e...
""" You are taking part in an Escape Room challenge designed specifically for programmers. In your efforts to find a clue, you've found a binary code written on the wall behind a vase, and realized that it must be an encrypted message. After some thought, your first guess is that each consecutive 8 bits of the code sta...
import string import re #def valid_username(username): # if username.isalpha(): # nameLength = len(username) # if nameLength > 3: # return #def valid_password(psw): # for char in psw: # if char.isalpha() and char.isdigit(): def valid_verifypsw(psw, vpsw): if psw == vpsw: ...
# -*- coding: utf-8 -*- """ CSV related help functions """ import csv import codecs from setup import eol, encoding delimiter = ';' def dict2csv(csv_path, a_dict): """Writes a dictionary to a csv file""" with codecs.open(csv_path, 'w', encoding) as csv_file: for (k, v) in a_dict.items(): ...
name = "John" x = 1 if x == 0: print("Bye bye") else: print("Hello", name)
from __future__ import print_function #class GameTreeNode: # def __init__(self, state): # self.state = state # full game state # self.value = 0. # value of node class FullGameTree: def __init__(self): self.state_val = {} #def create_tree(self, game): # game.clean() # ...
""" Simulate ingest application. This script fetch "california housing data set", samples some rows from it and add the sampled rows in the data file (CSV). Since this is just a prototype, we do not implement any complicated logic (such as stacking data set without duplicate). """ """ We should have a code for each d...
import random import unittest class Deck(object): class Card(object): def __init__(self, name, value, effect): self.name = name self.value = value self.effect = effect def __str__(self): return str(self.name) def __init__(self, file=None): ...
import re # This function takes in a line of text and returns # a list of words in the line. def split_line(line): return re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line) dictionary_list = [x for line in open('search_files/dictionary.txt') for x in split_line(line)] file = open('search_files/AliceInWonderLand200.tx...
import random # LOOPS (16pts TOTAL) # PROBLEM 1 (Fibonacci - 4pts) # The Fibonacci sequence is a sequence of numbers that starts with 1, followed by 1 again. # Every next number is the sum of the two previous numbers. # I.e., the sequence starts with 1, 1, 2, 3, 5, 8, 13, 21,... # Write a program that calculates and ...
import pandas import d3py from d3py.displayable import SimpleServer import logging """ This example is based on d3py_bar.py but the goal is to highlight how to configure a server for your figure. For the initial release, we simple support Python's SimpleHTTPServer. Got you sights on a different server? Look at the ...
""" Question: Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may as...
amount = 2400 transaction_type = "L" if transaction_type == "L": if amount <= 25000: discount = amount*.0 print( "Net Amount:", discount) if amount <=57000: discount = amount*.5 print( "Net Amount:", discount) else: if amount <=100000: discount = amount*.075 p...
s1=int(input("enter any num")) s2=int(input("enter any num")) s3=int(input("enter any num")) s4=int(input("enter any num")) sum=s1+s2+s3+s4 if(sum==360): print("it is trange") else: print("not trange")
#checkin.py #import pyperclip def bend(): #This function is used to determine if there is a bend, and if so, the severity weakBend = "Device has a minor bend in the frame." medBend = "Device has a moderate bend in the frame." strongBend = "Device has a severe bend in the frame." bend = eval(in...
#!/usr/bin/env python3 # coding: utf-8 class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height def get_volume(self): vol = self.length * self.width * self.height return vol box_one = Box(10, 20, 30) box_two = B...
#!/usr/bin/env python3 # coding: utf-8 # 1, 2, 3, 4, 5 # 2, 4, 6, 8, 10 # 3, 6, 9, 12, 15 # 4, 8, 12, 16, 20 # 5, 10, 15, 20, 25 size = int(input("How big would you like your times table? ")) for a in range(1, size + 1): for b in range(1, size + 1): product = a * b print("{}\t".form...
import unittest from calculator import Calculator class TestMyCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_initial_value(self): self.assertEqual(0, self.calc.value) # Creamos un nuevo test para comprobar una suma def test_add_method(self...
import sqlite3 db=sqlite3.connect("test.db") db.execute("drop table if exists results") try: db.execute("create table resultss(name,Class,section,telugu,hindi,english,maths,science,social)") except: print("already ") db=sqlite3.connect("test.db") #table created name="ashu" Class ="2" section="a" telugu="90"...
import pandas as pd #1 #This files purpose is to reclassify diseases as a more broad category. #This is done by iterating over the dataframe, and checking if the 6th item in each row is within the predefined list #Each predefined list is manually created and curated by user. #Each item in each predefined list shou...
#交叉验证的方法 from sklearn.datasets import load_iris; from sklearn.model_selection import train_test_split; from sklearn.neighbors import KNeighborsClassifier; import matplotlib.pyplot as plt; #进行交叉验证 from sklearn.cross_validation import cross_val_score; #加载数据集 iris = load_iris(); X = iris.data; Y = iris.target; #分割数据集 X...
''' Problem Statement url https://www.hackerrank.com/challenges/kangaroo/problem If v1<=v2 , they will never meet. It is required to check if a solution exists for the following equation: x1 + t*v1 == x2 + t*v2 This is equivalent to checking if : (x2-x1)%(v1-v2) == 0 ''' ''' solution ''' def kan...
import copy from random import shuffle class Sudoku: def __init__(self): self.grid = [[0 for i in range(9)] for j in range(9)] self.solved_path = [] @staticmethod def find_empty(grid): # Return empty row and col (or None if there is no empty one) for row in range(9): ...
#/usr/bin/python ''' Bond related objects and functions. ''' from numpy import * #? from matplotlib.pyplot import * #? from matplotlib.collections import LineCollection #? import pdb #? __all__=['Bond','BondCollection','show_bonds'] #__all__ can hide some class class Bond(object): '''A simple Bond class''' de...
tuple_ = (1,2,3) list_=[1,2,4] tuple_=tuple(list_) print(tuple_) list_[0]=77 a=[] tup = ([],) print(tup) tup[0].append(1) print(tup) a.append(12) print(tup)
def f(arg): # Рекурсия yield arg arg+=1 yield arg arg += 1 yield arg arg += 1 a = f(100) print(next(a)) print(next(a)) print(next(a)) '''''' def run(): print('run') def go(): print('go') def eat(): print('chav-vhav') a = {} a['run'] = run def error(): print('Error') if __na...
''' list_ = [1, 2, 3] list_.append(list_) # обект с бесконечностью, добавляет сам семя в конец бесконечое число раз print(list_) print(list_[-1]) for item in list_: print(item) if type(item) == list: for i in item: print(i) if isinstance(item, list): # то же самое, что и 7 строчка ...
x1=int(input()) y1=int(input()) #x2=int(input()) #y2=int(input()) if x>0 and y>0: print("I плоскасть") elif x<0 and y>0: print("II плоскасть") elif x<0 and y<0: print("III плоскасть") else: print("IV плоскасть")
#!/usr/bin/python3 import time def main(): print("Main Function") while True: oneHz(200) def hz(freq): fq = float(1 / freq) t0 = time.time() print(freq, " Hz") while True: if(time.time() > (t0 + fq)): break def oneHz(f): t0 = time.time() print("1 Hz") ...
from PIL import Image import face_recognition # https://github.com/ageitgey/face_recognition/tree/master/examples image1 = face_recognition.load_image_file("01_franzi_60er_gruppe.jpg") image2 = face_recognition.load_image_file("2018_07_30_F60_Schweizerhaus.jpg") image3 = face_recognition.load_image_file("17_matsch_ge...
#encoding: utf-8 __author__ = 'Josue Wuezo' class Human: def __init__(self): self.age = 25 #This an attribute print ('I am a human being') def talk(self, message): print (message) Leslie = Human() Michael = Human() Leslie.talk("Hello, Michael") Michael.talk("Oh\! H...
#Booleans, Logical Operators & Strings #True or False, 1 or 0 #Boolean: True or False // 1 or 0 bT = True bF = False print (str(bT) +' ' + str(bF)) #Logical Operators: AND (both are true) bA = True and False print (str(bA)) #Logical Operators: OR (at least one is true) bO = True or False print (str(bO)) #L...
una_lista = [1,2,3,4,5,6,7,8] for elemento in una_lista: print("Hola elemento Num 1", elemento) nombre = ["lara", "papa", "juan", "martin", "luis", "michelle", "pedro","lucia"] for alumnos in nombre: print("Hola alumno:", alumnos)
"""paying-the-minimum program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.""" balance = 4213 #credit card original balance annualInterestRate = 0.2 #constant annual interest rate monthlyPaymentRate = 0.04 #monthly ...
from bs4 import BeautifulSoup import requests import spotipy from spotipy import Spotify from spotipy.oauth2 import SpotifyOAuth time_travel = input("Enter the date you want to create Spotify playlist? Format YYYY-MM-DD") response = requests.get(f"https://www.billboard.com/charts/hot-100/{time_travel}") year_splice ...
letters = ('A','C','B','B','C','A','C','C','B') print(sorted(letters)) print(letters.count('A'),letters.count('B'), letters.count('C'))
""" Demo of a simple plot with a custom dashed line. A Line object's ``set_dashes`` method allows you to specify dashes with a series of on/off lengths (in points). """ import numpy as np import matplotlib.pyplot as plt labels = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11'...
#-*-coding:utf-8-*- """ python中字典和集合,无论是键还是值,都可以是混合类型。 字典支持索引操作,可以通过dict(['key'])或者dic.get('key')来访问value的值 集合不支持索引操作,其本质上是一个哈希表,和列表不一样。 字典和集合具有高效性,特别是对于查找、插入和删除操作。 之所以如此高效,因为字典和集合的内部结构都是一个张哈希表 字典:该表存储哈希值(hash)、键和值3个元素 集合:区别是哈希表没有键和值的配对,只有单一的元素 字典集合运用场景:对元素的高效查找、去重。 思考题: 1、 d ={'name':'jason','age':20,'...
n=int(input("enter the number=")) for i in range(n): for j in range((n//2)+1): if (j==0) or (i==0 or i==n-1): print("*",end=" ") else: print(" ",end=" ") print()
# Flash one LED - using python rev 3 # Writen by Ray Eacott import RPi.GPIO as GPIO # import import time GPIO.setmode(GPIO.BOARD) # set RPi to use pin numbers GPIO.setwarnings(False) # switch off error messages GPIO.setup(12, GPIO.OUT) # setup pin 12 as output for loop in range(1, 10): # repeat 10 time...
def ndigits(x): """ Counts the number of digits in x :param x: positive or negative integer to count digits from :return: number of digits in x """ if abs(x) < 10: return 1 return 1 + ndigits(abs(x)/10)
# Anything below here are for testing purpose only balance = 3329 annualInterestRate = 0.2 # End of testing stuff import math def calcEndOfYearBalance(balance, annualInterestRate, monthlyPayment): """ Calculates the credit card balance after one year for the given monthly payment :param balance: the out...
import math def primes(n=1000000): n = 1000000 arr = [True for x in xrange(0,n+1)] arr[0] = False # not prime arr[1] = False # not prime for i in xrange(2, int(math.sqrt(n))+1): pr = i # this is prime for j in xrange(2*pr, n+1, pr): arr[j] = False return (i for i i...
import math def how_many_divisors(n): num_divisors = 0 sq = int(math.sqrt(n)) for i in xrange(1,sq): if n%i == 0: num_divisors += 2 if n%sq == 0: num_divisors += 1 return num_divisors n = 1 while True: tr = n * (n+1) / 2 if how_many_divisors(tr) > 500: p...
import tkinter from tkinter import messagebox def wanna_quit(): if messagebox.askyesno("Quit", "Do you really want to quit?"): # the user clicked yes, let's close the window root.destroy() root = tkinter.Tk() root.protocol('WM_DELETE_WINDOW', wanna_quit) root.mainloop()
import functools import tkinter from tkinter import ttk def print_hello_number(number): print("hello", number) root = tkinter.Tk() big_frame = ttk.Frame(root) big_frame.pack(fill='both', expand=True) for i in range(1, 6): button = ttk.Button(big_frame, text="Hello %d" % i, command=f...
def linear_search(item,my_list): found = False i=0 while i<len(my_list) and found == False: if my_list[i] == item: found=True else: i=i+1 return found lista_prueba = [1,5,9,15,25,346,932] print(linear_search(65,lista_prueba)) print(linear_search...
def chocolateFeast(n, c, m): chocolates = n // c wrappers = n // c while wrappers >= m: chocolates += wrappers // m wrappers = (wrappers // m) + (wrappers % m) return chocolates if __name__ == '__main__': t = int(input()) for test in range(t): ncm = [int(inp) for inp in input().split()] n = ncm[0] c =...
def collatz(n): while n != 1: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 return True if __name__ == '__main__': for i in range(1, 10000): print("{}: ".format(i) + str(collatz(i)))
def powerSum(X, N, count): if count<((X**0.5)+1): if X<0: return 0 elif X==0: return 1 if (X-(count**N))>=0: return powerSum(X-(count**N),N,count+1)+powerSum(X,N,count+1) else: return powerSum(X,N,count+1) return 0 X = int(input()) N = int(input()) count = 1 result = powerSum(X, N,count) pr...
class Node: def __init__(self, value): self.value = value self.parent = None self.left = None self.right = None class BST: def __init__(self): self.root = None def insert(self, value): if self.root == None: self.root = Node(value) else: return self._insert(self.root, value) def _insert(self...
def partition(array: list) -> list: p = array[0] less = [] grt = [] for i in range(1, len(array)): if array[i] < p: less.append(array[i]) else: grt.append(array[i]) ans = quickSort(less) + [p] + quickSort(grt) print(' '.join(map(str, ans))) return an...
def sequenceEquation(n, inp): ans = list() for i in range(1, n + 1): x = inp.index(i) + 1 ans.append(inp.index(x) + 1) return ans if __name__ == '__main__': n = int(input()) inp = [int(i) for i in input().split()] for i in sequenceEquation(n, inp): print(i)
def timeInWords(h,m): words = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty si...
#!/bin/python3 import os import sys def handshake(n): sum1 = 0 for i in range(n-1,0,-1): sum1 += i return sum1 t = int(input()) for t_itr in range(t): n = int(input()) result = handshake(n) print(result)
def versionCheck(version1, version2): if version1[0] > version2[0]: return True elif version1[0] < version2[0]: return False elif len(version1) > 1: return versionCheck(version1[1:], version2[1:]) else: return 'Same' if __name__ == '__main__': version1 = [int(i) for i in input('Enter version1: ').split('....
def countingValleys(n, s): start = 0 valleys = 0 for i in range(len(s)): if s[i] == 'U': start += 1 elif s[i] =='D': if start == 0: valleys += 1 start -= 1 return valleys n = int(input()) s = input() result = countingValleys(n, s) print(result)
from math import sqrt, ceil def checkPrime(num): if num == 1: return False elif num == 2: return True elif num % 2 == 0: return False for i in range(3, ceil(sqrt(num)) + 1): if num % i == 0: return False return True def sortPrime(inp): inp.sort() ...
import math def func(x,y): return (y-1)**(0.5) pi = 3.14159 a = 0 b = 2 h = (b-a)/4 x = 0 y = 5 while x!=b: y1 = y + h*func(x,y) print(y1) y = y + (h/2)*(func(x,y)+func(x+h,y1)) print(y) x+=h
#Object Oriented Programming class Employee: raiseAmount = 1.05 empNum = 0 def __init__(self, first: str, last: str, pay: float) -> None: self.first = first self.last = last self.email = first + '.' + last + '@company.com' self.pay = pay Employee.empNum += 1 def getFullName(self) -> None: return sel...
def checkJulianLeap(year): if year%4==0: return True else: return False def checkGeorgianLeap(year): if year%400==0: return True elif year%100==0: return False elif year%4==0: return True def solve(year): if year == 1918: return("26.09." + str(year)) elif year < 1918: if checkJulianLeap(year): ...
import deck import human import ai import RandAI import random import hand_graph import reduce_ai import better_bogo import compete_ai """ What do we need to run a game of five crowns? Initialize the deck each round to a shuffled state Keep track of the round to know how many cards to deal out. Need to be able to sto...
import player import hand_graph POINT_VAL = 1 class Player(player.Player): def draw(self, game): self.hand.append(game.discard) def discard(self, game): groups = self.build_groups() worst_set = groups[0] # Checks if there is a card that is not connected to anything else. ...
# -*- coding: utf-8 -*- """ Created on Thu Oct 6 20:11:55 2016 @author: xzx @refer to Andrew Ng's code in Machine Learning class in coursera """ import numpy as np import math import matplotlib.pyplot as plt def sigmoid(z): return 1.0 / (1.0 + np.exp(-z)) def nnCostFunction(Theta1,Theta2,\ ...
for i in range(5): print(i) for i in range(11, 19): print(i) # a step with range print(range(10, -100, -30)) # iterate over indices of a sequence # combine range() and len() a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(len(a)): print(i, a[i]) # behaves as a list but it isn't # it doesn't make t...
#Practice Chapter 5 - Modules + Turtle print("Jedi Turtle") import turtle turtle.forward(20) turtle. speed(50000000000000000) from turtle import * color('red', 'yellow') begin_fill() pensize(2) while True: forward(200) left(230) right(300) if abs(pos()) < 1: break end_fi...
# -*- coding: utf-8 -*- """ Created on Fri Jul 15 15:56:54 2022 @author: Aster Taylor This script provides a demonstration of how to add functions to the SAMUS class which provide data outputs. All functions must either take no inputs or take 'self', and use class variables. This script provides examples of b...
import os from utils import StringDistance, extract_digit class GenderCorrection: """Correct Religion based on input by comparing Levenshtein distance to tongiao.txt """ def __init__(self, cost_dict_path=None, gender_path = None): dir_path = os.path.dirname(os.path.realpath(__file__)) ...
from ..algebra import AABB, Vector from ..fields import Cell, CellInterval def map_aabb_to_cell_interval(aabb, field_orig, field_res, field=None): """Maps an ``aabb`` to a ``CellInterval``of the ``field``. Parameters ---------- aabb: AABB The domain to be mapped. field_orig: Vector f...
import re # 1-3 a: abcde is valid: position 1 contains a and position 3 does not. # 1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b. # 2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c. x = 0 y = 0 passWords = open('day2.input') for line in passWords: policy = re.find...
from numpy import arange import random from math import ceil # code for emulating competitions with different difficulty levels # we will add the levels of the competition and their difficulty coefficient to the dictionary lvl_compt = { 'street': [0.95, 0.0375, 0.0125, 0, 0], 'town': [0.6, 0.3, 0.1, 0, 0], ...
import random import sys import time from decimal import Decimal from discount_rules import buy_two_apples_get_one_free, five_off_when_you_spend_hundred_or_more from enums import UnitType from factories import GroceryFactory from objects import Grocery, Basket, Store, Discount def _random_price(): return round(D...
# # we want to show in e.g. M if there is at least 1 M, that is, optimal so that # number/(1000^optimalExp) >= 1 # mathematics->logarithms-> # optimalExp = log(number) / log(1000); # import math units = ['','k','M','G','T','P','E','Z','Y'] def formatNumber (number, decimals = 2) : optimalExp = ...
import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np def evaluate_agents(num_runs, num_steps, agents, mab, agent_names=None): """ Function to call each agent on a given MAB for a pre-specified number of runs and timesteps for each run. By comparing these multipl...
for n in range(11): print(n) controlador = 0 while (controlador <= 10): print(controlador) controlador += 1
products = [] while True: name = input ("Fil in the product name: ") if name == "q": break price = input ("Fill in the product price: ") products.append([name, price]) print(products) for p in products: print(p[0], "price is", p[1])
from functools import reduce class Matrix(list): """ По своей сути обычный список с дополнительной проверкой в конструкторе и методом """ def __init__(self, matrix): if len(matrix) != len(matrix[0]): raise ValueError('Идиот, матрица должна быть квадратной') super().__init__...
def yes_or_no(): count = 2 while True: if count % 2: yield 'no' else: yield 'yes' count += 1 def yes_or_no(): answer = "yes" while True: yield answer answer = "no" if answer == "yes" else "yes" gen = yes_or_no() print(...
def be_polite(fn): def wrapper(): print("What a pleasure to meet you!") fn() print("Have a great day!") return wrapper @be_polite def greet(): print("My name is Norberto.") @be_polite def rage(): print("I HATE YOU!") greet = be_polite(greet) polite_rage = be_polite(ra...
# Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print(f"X = {X}") print(f"Y = {Y}") print() # Split Dataset: Training Set and Test Set from sklearn.model_...
#Using list comprehension def triple_and_filter(listOfNums): return [num * 3 for num in list(filter(lambda x: not x % 4, listOfNums))] #Using map function def triple_and_filter(lst): return list(filter(lambda x: x % 4 == 0, map(lambda x: x*3, lst))) print(triple_and_filter([1, 2, 3, 4]))
class User: active_users = 0 def __init__(self, first, last, age): self.first = first self.last = last self.age = age User.active_users += 1 def __repr__(self): return f"{self.first} is {self.age}" @classmethod def display_active_us...
message = input('Hey, how\'s it going? ').lower() while message != 'stop copying me': print(message) message = input().lower() print('UGH FINE YOU WIN')
from functools import wraps def double_return(fn): @wraps(fn) def wrapper(*args, **kwargs): result = fn(*args, **kwargs) return [result, result] return wrapper @double_return def add(x, y): return x + y print(add(1, 2)) @double_return def greet(name): return "Hi, I'm " +...
from csv import DictReader with open("fighters.csv") as file: csv_reader = DictReader(file) for row in csv_reader: print(row['Name']) from csv import DictReader with open("fighters_other_delimiter.csv") as file: csv_reader = DictReader(file, delimiter = "|") for row in csv_reader: ...
class BankAccount: def __init__(self, owner): self.owner = owner self.balance = 0.0 def getBalance(self): return self.balance def deposit(self, amount): self.balance += amount return self.balance def withdraw(self, amount): self.balance ...
student = { 'name': 'Norberto', 'owns_parrot' : True, 'favorite_language': 'Python', 25 : 'my favorite number!'} print(f'{student =}') parrot = {'name': 'Lorenzo', 'age': 1.5, 'isLoco': True} print(f'{parrot =}') car = dict(name = 'pegasus', age = 1.0) print(f'{car = }')
#List of Numbers more_numbers = [6, 1, 8, 2] print(f'more_numbers = {more_numbers}') print(f'sorted more_numbers = {sorted(more_numbers)}') print(f'sorted more_numbers in reverse = {sorted(more_numbers, reverse = True)}') #Dictionary users = [ {"username": "samuel", "tweets": ["I love cake", "i love fruit"]}, ...
# Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Data.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print(f"X = {X}") print(f"Y = {Y}") print() # Convert Y to 2D Array for Feature Scaling Y = Y.reshape(len(Y), 1) ...
# Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Data.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print(f"X = {X}") print(f"Y = {Y}") print() # Split Dataset: Training Set and Test Set from sklearn.model_selecti...
class User: active_users = 0 @classmethod def display_active_users(cls): return f"There are currently {cls.active_users} active users." @classmethod def from_string(cls, data_str): first, last, age = data_str.split(",") return cls(first, last, int(age)) ...
class Animal(): def speak(self): raise NotImplementedError("Subclass needs to implement this method") class Dog(Animal): def speak(self): return "woof" class Cat(Animal): def speak(self): return "meow" class Fish(Animal): pass d = Dog() print(d.spe...
# Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print(f"X = {X}") print(f"Y = {Y}") print() # Split Dataset: Training Set and Test Set X_train = X[:...