text stringlengths 5 121k |
|---|
class Bookshelf:
def __init__(self, *books):
self.books = books
def __str__(self):
return f"There are {len(self.books)} books."
class Book:
def __init__(self, name, amount):
self.name = name
self.amount = amount
def __str__(self):
return f"Book name is {self.n... |
import requests
import json
import time
import sys
import matplotlib.pyplot as plt
URL="https://www.quandl.com/api/v3/datasets/CFTC/0233CV_FO_L_ALL_CR.json?api_key={:s}&".format(key)
parameters = {'start_date': '2020-01-01', 'end_date':'2020-12-31'}
response = requests.get(URL, params=paramet... |
"""
Created on Thu Aug 19 15:30:29 2021
@author: Comp
"""
list1 = [-12 , -7 , 5 ,64 , -14]
for num in list1:
if num >= 0:
print(num, end = " ") |
def double(x):
return x*2
print(double(3))
def multiply(a, b):
result = a * b
print("the result of a * b")
return result
result = multiply(2, 3)
print(result)
|
from ssearch_while import seq_search
print("Finding a float.")
print("Caurtion: the program quits when 'End' entered")
number = 0
x = []
while True:
s = input(f'x[{number}]: ')
if s == "End":
break
x.append(float(s))
number += 1
ky = float(input("What to search?: "))
idx = seq_search(x,... |
def qsort(a, left, right):
n = len(a)
pl = left
pr = right
x = a[(left+right)//2]
while pl <= pr:
while a[pl] < x: pl += 1
while a[pr] > x: pr -= 1
if pl <= pr:
a[pl], a[pr] = a[pr], a[pl]
pl += 1
pr -= 1
if left < pr: qsort(a, left, pr)
if right > pl: qsort(a, pl, right)
return a
def... |
def sort3(a, idx1, idx2, idx3):
if a[idx2] < a[idx1]: a[idx1], a[idx2] = a[idx2], a[idx1]
if a[idx3] < a[idx2]: a[idx2], a[idx3] = a[idx3], a[idx2]
if a[idx2] < a[idx1]: a[idx1], a[idx2] = a[idx2], a[idx1]
return idx2
def insertion_sort(a, left, right):
for i in range(left+1, right+1):
j=i
tmp = a[i]
w... |
from enum import Enum
from fixed_stack import FixedStack
Menu = Enum("Menu",['push','pop','peek','find','dump','quit'])
def select_menu() -> Menu:
s = [f'({m.value}){m.name}' for m in Menu]
while True:
print(*s, sep = ' ', end = '')
n = int(input(': '))
if 1 <= n <= len(Menu):
... |
from nltk.tokenize import sent_tokenize
def lines(a, b):
"""Return lines in both a and b"""
a_line = set(a.split("\n"))
b_line = set(b.split("\n"))
return list(a_line & b_line)
def sentences(a, b):
"""Return sentences in both a and b"""
a_sentence = set(sent_tokenize(a))
b_sentence = ... |
import pandas as pd
import numpy as np
def cargar_datos(path:str):
"""
dado el path, retorna una tupla con= un numpy.narray primer array filas, segundo array valores de las columnas
con= numpy.narray donde solo tiene valores de la ultima columna del dataset.
"""
data_set_diabetes = pd.read_csv(path... |
import numpy as np
def entrenar(red_neuronal, Entrada, Respuesta, funcion_costo, tasa_aprendizaje=0.05, entrenar=True):
"""Si entrenar esta en true, se obtiene los resultados del forward_pass, luego se hace el proceso de backpropagation
donde se calculan los deltas, y luego con esto se realiza el aprendizaje ... |
a=int(input())
b=int(input())
if(a>b):
print(a)
elif(a==b):
print("Oni ravny")
else:
print(b)
|
lst = [(1, 2), (2, 2), (3, 2)]
print(lst[1][0])
for i in range(0,3):
print(lst[i])
i+=1 |
'''
This file contains the definitions of tokens required
to tokenize the program
'''
import ply.lex as lex
def build_lexer(debug_mode=True, optimize_mode=False):
tokens = [
'IDENTIFIER',
'UNION',
'INTERSECTION',
'DIFFERENCE',
'INTEGER'
]
literals = "(),"
... |
def rotate(s, k):
duble_s = s + s
if k <= len(s):
return duble_s[k:k+len(s)]
else:
return duble_s[k-len(s):k]
print(rotate("ali", 5)) |
"""
buy-sell stock
[7, 1, 5, 3, 6, 4] ==> 5
[9, 7, 6, 4, 3, 1] ==> 0
"""
def max_profit(prices):
cur_max, final_max = 0, 0
for i in range(1, len(prices)):
cur_max = max(0, cur_max + prices[i] - prices[i - 1])
final_max = max(cur_max, final_max)
return final_max
max_profit([... |
"""
BaseURLManager定义文件
"""
from threading import Thread
from abc import ABC, abstractmethod
from base.utilities import Logger
class BaseURLManager(ABC):
"""
从目录页获取文章URL,为Spider提供待爬取的URL
"""
def __init__(self, start_page=1, end_page=-1):
"""
初始化
注意:每个目录页包含多个url
:param... |
"""
Question:You are given an array arr[] of N integers including 0.
The task is to find the smallest positive number missing from the array.
Example 1:
Input:
N = 5
arr[] = {1,2,3,4,5}
Output: 6
Explanation: Smallest positive missing number is 6.
Example 2:
Input:
N = ... |
import numpy as np
start = input("start from : ")
end = input("end with : ")
number = int(np.random.randint(int(start), int(end)+1))
g = int(input("Input your guess here : "))
while g != number:
if g > number:
print("The number is smaller")
g = int(input("Give another guess : "))
else:
... |
import os
import numpy as np
import tensorflow as tf
from PIL import Image
from matplotlib import pyplot as plt
print('Using TensorFlow', tf.__version__)
generator = tf.keras.preprocessing.image.ImageDataGenerator(rotation_range=40)
image_path = 'images/train/cat/cat.jpg'
plt.imshow(plt.imread(... |
import csv
from participant import Participant
import sys
class Reader:
"""
Reader class for the .csv files
Currently, a minimum number of 18 participants is required
"""
def __init__(self, file, delimiter=","):
self.file = file
self.delimiter = delimiter
def check_header(sel... |
import numpy as np
user_input=int(input())
n=user_input
list=[]
while(n!=0):
m=n%10
n=n/10
list.append(m)
list.reverse()
numpy_array=np.array(list)
numpy_array.sort()
numpy_array=numpy_array[::-1]
print(numpy_array)
|
from sys import argv as ag
def addToNumbers( number1, number2 ):
print('StartProgram: addToNumbers executed...\n')
result = number1+number2
return result
answer = False
def isEven( aNumber ):
if( aNumber%2 == 0 ):
return True
... |
import mapquest_api
import mapquest_classes_output
class MapQuestError(Exception):
pass
class RouteNotFoundError(Exception):
pass
def input_places() -> list:
'''let user input the locations and orders'''
places_num = int(input())
if places_num < 2:
raise MapQuestError
else:
... |
def runtest(c):
while True:
j = [str(i) for i in input().split()]
if j[0] == "what":
print (" ".join(c))
return
else:
c = [value for value in c if value != j[-1]]
for n in range(0, int(input())):
runtest([str(i) for i in input().split()])
|
import pygame
import random
from helps import Common, width, height
from base_classes import *
class Board(pygame.sprite.Sprite, GameObject):
"""
Class describing behavior of board object
Class inherits GameObject class
Attributes:
step step of moving by key
"""
def __init__(s... |
import sys
def caesarEncrypt(plainText, numShift):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
key = []
cipherText = ''
plainText = plainText.lower()
for i in range(len(alphabet)):
if i + numShift >= 27:
key.append(alphabet[i + numShift - 27])
else:
key... |
def solution(digits):
return max(int(digits[i:i + 5]) for i in range(len(digits)))
print(solution('1234567898765')) |
"""
Created on Wed Feb 20 19:47:56 2019
@author: stbrb@mst.edu
"""
import sys
def main():
keyFile = sys.argv[1]
keyNum = sys.argv[2]
inFile = sys.argv[3]
outFile = sys.argv[4]
convertedString = convertInput(inFile)
binaryString = getOtpKey(keyFile, keyNum)
XORString= XOR(convert... |
from zipfile import ZipFile
zip = ZipFile('ch6.zip', 'r');
print(zip.getinfo('90052.txt').comment);
pathPrefix = 'ch6/';
fileType = '.txt';
filename = "90052";
fileContents = open(pathPrefix + filename + fileType, "r").read();
filename = fileContents[fileContents.index('is') + 3:];
print(str(zip.getinfo(filename + f... |
from slowEngine.vector2 import Vector2
class Camera:
""" Camera class.
Uses singleton pattern.
Deals with game/world display things.
"""
_instance = None
@staticmethod
def get_instance():
if Camera._instance is None:
Camera()
return Camera._instance
d... |
""" oopRectangle.py
intro to OOP by building a Rectangle class that demonstrates
inheritance and polymorphism.
"""
def main():
print ("Rectangle a:")
a = Rectangle(5, 7)
print ("area: {}".format(a.area))
print ("perimeter: {}".format(a.perimeter))
print ("")
print ("Rectan... |
def recite(start, take=1):
song=[]
while take>0:
if start==0:
song.append('No more bottles of beer on the wall, no more bottles of beer.')
song.append('Go to the store and buy some more, 99 bottles of beer on the wall.')
elif start==1:
song.append('1 bottle of beer on the wall,... |
from string import ascii_uppercase as UPPER
def make_diamond(letter):
diamond=[]
for i in range(UPPER.index(letter)+1):
if i==0:
diamond.append((UPPER.index(letter)-i)*' '+UPPER[i]+(UPPER.index(letter)-i)*' ')
else:
diamond.append((UPPER.index(letter)-i)*' '+UPPER[i]+(i*2-1)*' '+UPPER[i]+(UPPER.index(lette... |
class Allergies(object):
def __init__(self, score):
self.score=score
def is_allergic_to(self, item):
return (item in self.lst)
@property
def lst(self):
allergy_list=[]
temp_score=self.score%256
while temp_score>0:
if temp_score>=128:
temp_score-=128
allergy_list.append('cats')
... |
class CustomSet(object):
def __init__(self, elements=[]):
self.elements=set(elements)
def isempty(self):
return not self.elements
def __contains__(self, element):
return element in self.elements
def issubset(self, other):
return self.elements <=other.elements
def ... |
"""
Constructing and loading dictionaries
"""
import numpy
from collections import OrderedDict
from collections import Counter
def build_dictionary(text):
"""
Build a dictionary
text: list of sentences (pre-tokenized)
"""
counter = Counter()
captions = []
for s in text:
tokenized_captions = []
s = s.lower()... |
"""
Created on Wed Feb 20 22:53:14 2019
@author: Ankur Singh
"""
"""
Python is easy : Homework assignment #9
Classes
"""
class Vehicle:
def __init__(self, make, model, year, wt, TSM, NM):
self.make = make
self.model = model
self.year = year
self.weight ... |
"""
Created on Sat Feb 9 23:48:15 2019
@author: New
"""
"""
Python is easy: Homework assignment #6
Advanced Loops
"""
def playingBoard(rows,columns):
if rows<=15 and columns<=15:
for r in range(1,rows):
if r % 2 == 0:
for c in range(1... |
import csv
comparator_ops = ["min", "max"]
math_ops = ["sum", "avg"]
valid_op_names = comparator_ops + math_ops
def evaluate_sheet(column_name, op_name, fn="data.csv"):
result = None
try:
with open(fn, "r") as d:
cr = csv.reader(d, delimiter=",")
op_index = valid... |
"""
Question:
You have 15 six-sided blocks.
These are cubes with a letter (or a blank space) on each face.
Each block can have a different set of letters.
For instance, one block may have A E I O U _ on its faces;
another block may have A B C D E E.
Write a function that takes as input a 15 character message
and t... |
def precedence(op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/':
return 2
return 0
def applyOp(a, b, op):
if op == '+': return a + b
if op == '-': return a - b
if op == '*': return a * b
if op == '/': return a // b
def evaluate(tokens):
values = []
ops = ... |
import sqlite3
class Sqlite3DB:
def __init__(self, db_name=None):
self.conn = sqlite3.connect(db_name if db_name else 'system.db')
self.cursor = self.conn.cursor()
def create_table(self, table_name: str, field_list: list):
"""
创建表格
:param table_name: 表名
:param... |
def error(index_error):
list_error = {
'Bad file': 'Error: Bad file',
'Unsolvable': 'Error: Puzzle is unsolvable',
'Under size': 'Error: Size must be ≥ 3',
'Under shuffle': 'Error: Number of shuffle must be ≥ 0',
}
print(list_error[index_error])
exit(1)
def swap(data, i1, i2):
data[i1], data[i2] = data[i2... |
import pandas
import pandas as pd
class CSVStepsArrayLoader(object):
@staticmethod
def load(file_path):
try:
df = pd.read_csv(file_path, sep=',', header=None, skip_blank_lines=True).dropna()
except pandas.errors.EmptyDataError:
raise pandas.errors.EmptyDataError('No dat... |
"""Softmax."""
import numpy as np
scores = np.array([3.0, 1.0, 0.2])
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
values = np.exp(x);
return values/np.sum(values,axis=0)
"""
long method
if len(np.shape(values))>1 :
values_t = np.transpo... |
import numpy as np
def predict(X, w):
return np.matmul(X, w)
def loss(X, Y, w):
return np.average((predict(X, w) - Y) ** 2)
def gradient(X, Y, w):
return 2 * np.matmul(X.T, (predict(X, w) -Y)) / X.shape[0]
def train(X, Y, iterations, lr):
w = np.zeros((X.shape[1], 1))
for i in range(iteratio... |
def input1():
message = input("Please enter the message: ")
cora = input("Is the message in caesar or english? c or e: ")
if cora == "c":
shift = -3
else:
shift = 3
return message,shift
def process(message,shift):
list1 = list(message)
list2 = []
for index in range(... |
list1= []
item = '1'
while item!= "0":
item=input("Please add an item to a list: ")
if item!= "0":
list1.append(item)
no_swaps=False
while no_swaps != True:
no_swaps= True
for count in range (len(list1)-1):
if list1[count]> list1[count+1]:
no_swaps = False
... |
from electron_rk4_1 import *
import numpy as np
import matplotlib.pyplot as plt
Ex = 0
Ey = 0
B = 1e-4
t0 = 0.0
dt = 1e-9
tmax= 1e-6
x0=0.0
y0=0.0
vx0=100
vy0=0.0
ode = ElectronRK4([x0, y0, vx0, vy0], dt, t0, Ex, Ey, B)
ode.iterate(tm... |
"""
This is a program that encodes any text using the ROT13 cipher.
You need 2 files in the same dir with this script: text.txt and result.txt. Write your text in text.txt, run the script and you will get the encoded version in result.txt.
Usage:
sys_argv.py -i <text.txt> -o <result.txt>
"""
import sys, codecs
... |
class Diver(object):
""" Main diver class """
def __init__(self, diver_name):
""" Initialize diver class """
self.name = diver_name
self.choices = {
'instructor_name': 'x',
'cave_name': 'y',
'equipment': []
}
self.points = None
... |
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers availa... |
print("Mary had a little lamb.")
print("Its fleece was white as {}.".format('snow'))
print("And everywhere that Mary went.")
print("." * 10)
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
print(end1 + end2 + end3... |
import argparse
import codecs
import os
def write_result(args, encoded):
""" Write result to the output file """
result = args['text'][:-4] + '_1.txt'
with open(result, 'w') as target:
target.write(encoded)
target.close()
print("Success! Your file is encoded.")
def encode(args):
... |
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man that's enough for a party!")
print("Get a blanket.\n")
print("We can just give the function numbers directly:"... |
def range_func(incr, up_limit):
numbers = []
numbers = range(incr, up_limit)
for number in numbers:
print(f"The number is {number}")
print("The numbers: ")
for number in numbers:
print(number)
range_func(1, 6) |
def temp_after_one_hour(t_room, t_cond, mode):
if mode == 'fan':
return t_room
elif mode == 'auto':
return t_cond
elif mode == 'freeze':
if t_cond < t_room:
return t_cond
else:
return t_room
elif mode == 'heat':
if t_cond > t_room:
... |
"""
util.py -- Common functions to be used by various sorting algorithms.
"""
import random
def swap(l, i, j):
"""
Swap the index i with the index j in list l.
Args:
l (list): list to perform the operation on.
i (int): left side index to swap.
j (int): Right side index to... |
"""
binary_search_rotated_array.py
Author: Corwin Brown <blakfeld@gmail.com>
"""
from __future__ import print_function
import sys
import utils
def binary_search(list_to_search, num_to_find):
"""
Perform a Binary Search on a rotated array of ints.
Args:
list_to_search (list): The list to sear... |
import matplotlib.pyplot as plt
from matplotlib import style
style.use('bmh')
x = [2, 4, 6]
y = [3, 6, 9]
x2 = [4, 8, 12]
y2 = [5, 10, 15]
x3 = [6, 12, 18]
y3 = [12, 24, 36]
plt.bar(x, y)
plt.bar(x2, y2)
plt.bar(x3, y3)
plt.title("Test")
plt.xlabel("Test x values")
plt.ylabel("Test y values")
plt.show()
print("... |
rainbow = ["red", "orange", "green", "yellow", "blue", "black", "white", "aqua", "purple", "pink"]
del rainbow[5:8]
rainbow[2:4] = ["yellow", "green"]
rainbow[4:5] = ["blue", "indigo"]
rainbow[-2:] = "violet"
rainbow[-6:] = ["".join(rainbow[-6:])]
for i in rainbow:
print (i)
|
import csv
from typing import Union, IO, List, Dict, Generator, Iterable, ByteString, Optional
def process_csv(file: Union[IO, str, List[str], bytes]):
if isinstance(file, bytes):
file = file.decode()
if isinstance(file, str):
file = file.splitlines()
return csv.DictReader(file, delimiter=... |
i=1
while i<=4:
j=1
while j<=7:
if (i==1 and(j==1 or j==2 or j==3 or j==5 or j==6 or j==7)):
print(" ",end=" ")
elif(i==2 and(j==1 or j==2 or j==6 or j==7)):
print(" ",end=" ")
elif(i==3 and(j==1 or j==7)):
print(" ",end=" ")
else:
... |
i=20
while i<=100:
if i%2==0:
print(i ,"divisible by 2")
i=i+1
|
i=0
sum=0
n=int(input("enter a number"))
while i<n:
n_1=int(input("enter a number"))
sum=sum+n_1
print(sum)
i=i+1
|
def sum_of_square(min_int, max_int):
list_out=[]
for x in range(min_int, max_int+1):
list_out.append(x**2)
return sum(list_out)
def square_of_sum(min_int, max_int):
list_out=[]
for x in range(min_int, max_int+1):
list_out.append(x)
return sum(list_out)
print(((square_of_... |
import json
from datetime import date, timedelta
class JsonFile:
def __init__(self, path):
self.path = path
def read(self):
with open(self.path, "r") as f:
data = json.load(f)
return data
def write(self, data):
with open(self.path, "w") as f:
json... |
T = int(input())
w, h = 100, 100;
arr = [[0 for x in range(w)] for y in range(h)]
for i in range(T):
N = int(input())
for L in range(N+1):
for m in range(L):
arr[L][m] = int(input())
'''
for L in range(N+1):
for m in range(L):
print(arr[L][m], end=" ")
print()
'''
|
def fact(n):
f=1
for i in range(1,n):
f=f*i
return f
n=int(input("Enter a number"))
print(fact(n))
|
T = int(input())
for i1 in range(T):
notes = [1,2,5,10,50,100]
notes = reversed(notes)
sum1 = int(input())
count = 0
for item in notes:
while sum1 >= item:
sum1 -= item
count += 1
print(count)
|
"""
demo01_ndarray.py numpy演示
"""
import numpy as np
ary = np.array([1, 2, 3, 4, 5, 6])
print(ary, type(ary))
print(ary + 10)
print(ary * 3)
print(ary + ary)
|
edad=input("Ingrese su edad")
a=int(edad)
if a >= 18:
print("Eres mayor de edad ")
else:
print("Eres mmenor de edad ") |
from pynput.mouse import Listener, Button
def on_click(x, y, button, pressed):
"""Print the cursor position when the left mouse button is clicked"""
if pressed and button == Button.left:
print("Mouse Clicked: (%d, %d)" %(x, y))
listener.stop()
with Listener(on_click=on_click) as listene... |
from lat3 import Manusia
import datetime
class SiswaSMA(Manusia):
"""Class Mahasiswa yang dibangun dari class Manusia."""
def __init__(self,nama,NIS,kota,umur,us):
"""Metode inisiai ini menutupi metode inisiai di class Manusia."""
self.nama = nama
self.NIS = NIS
self.kota... |
import unittest
from Calculator.Calculator import Calculator
class MyTestCase(unittest.TestCase):
def test_instantiate_calculator(self):
calculator = Calculator()
self.assertIsInstance(calculator, Calculator)
def test_calculator_addition(self):
calculator = Calculator()
resu... |
def merge(nums1,m,nums2,n):
last =m+n-1
while m>0 and n>0:
if nums1[m-1]>nums2[n-1]:
nums1[last]=nums1[m-1]
m-=1
else:
nums1[last]=nums2[n-1]
n-=1
last-=1... |
'''def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}"
def print_one(arg1):
print(f"arg1: {arg1}")
def print_none():
print("I got nothin'.")
print_two("Zed","Shaw")'''
'''def function(x, y, z):
ans... |
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
lenA = 0
lenB = 0
pointerA = headA
pointerB = headB
while headA is not None:
headA = headA.next
lenA +=1
while headB i... |
print("Classe character bien importee")
class Character:
def __init__(self, nom, prenom, age, profession, boostDeMoral):
self.nom = nom
self.prenom = prenom
self.age = int(age)
self.profession = profession
self.boostDeMoral = float(boostDeMoral)
... |
cubes = [1**3, 2**3, 3**3, 4**3, 5**3, 6**3, 7**3, 8**3, 9**3, 10**3]
for value in cubes:
print(value)
|
"""Class user"""
class Person():
"""Model a Person."""
def __init__(self, first_name, last_name):
"""Initialize first_name and last_name attribute."""
self._first_name = first_name
self._last_name = last_name
@property
def first_name(self):
"""first_name property"""
... |
"""Class user"""
class Person():
"""Model a Person."""
def __init__(self, first_name, last_name):
"""Initialize first_name and last_name attribute."""
self._first_name = first_name
self._last_name = last_name
@property
def first_name(self):
"""first_name property"""
... |
favorite_fruits = ['mango', 'guava', 'strawberry']
if 'mango' in favorite_fruits:
print("You really like mango!")
if 'guava' in favorite_fruits:
print("You really like guava!")
if 'strawberry' in favorite_fruits:
print("You really like strawberry!")
if 'blueberry' in favorite_fruits:
print("You reall... |
"""Draw a circle
"""
import math
import turtle
def draw_circle_turtle(x, y, r):
"""Draw the circle using turtle
"""
turtle.up()
turtle.setpos(x + r, y)
turtle.down()
for i in range(0, 361, 1):
a = math.radians(i)
turtle.setpos(x + r * math.cos(a), y + r * math.sin(a... |
numbers = list(range(1, 6))
print(numbers)
|
"""Programming poll."""
path_file = "text_files/programming_poll.txt"
print("Write 'quit' to exit")
while True:
answer = input("Why do you like programming? ")
if answer == "quit":
break
if answer:
with open(path_file, 'a') as file_object:
file_object.write(answer + '\n')
|
current_users = ['anonymous', 'webmaster', 'admin', 'dbadmin', 'humberto']
new_users = ['guest', 'WEBMASTER', 'postgres', 'humberto', 'elliot']
for new_user in new_users:
if new_user.lower() in current_users:
print("You need to enter a new username")
else:
print("Username " + new_user + " is... |
"""Class user"""
class Privileges():
"""Model for privileges."""
def __init__(self, privileges):
"""Initialize privilege attributes."""
self.privileges = privileges
def show_privileges(self):
"""Display user's privileges."""
print("Privileges".center(17))
for priv... |
my_pizzas = ['neapolitan', 'california style', 'chicago deep dish',
'chicago thin crust', 'detroit style', 'new england greek',
'new york thin crust', 'st. louis style', 'new jersey style']
friend_pizzas = my_pizzas[:]
my_pizzas.append('pepperoni')
friend_pizzas.append('hawaiian')
... |
"""Class Restaurant"""
class Restaurant():
"""Class that represent a restaurant."""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize restaurant_name and cuisine_type attributes."""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.num... |
import random
def check_order(a, increase=True):
l = len(a)
for i in range(l-1):
if (a[i] > a[i+1]) == increase:
return False
return True
def init_arr(length, min_value = -100, max_value=100):
a = [0] * length
for i in range(length):
a[i] = random.randint(min_value, ... |
import random
print("Ingrese cuantos numeros aleatorios desea obtener")
n=int(input())
vector = [random.randint(0,1000) for _ in range(n)]
print ("vector desordenado")
print(vector)
def bubble_sort(vector):
permutation = True
iteración = 0
while permutation == True:
permutation = False
... |
"""
Python’s random module includes a function shuffle(data) that accepts a list of elements and randomly reorders the elements so that each possi- ble order occurs with equal probability. The random module includes a more basic function randint(a, b) that returns a uniformly random integer from a to b (including both ... |
"""
Demonstrate how to use Python’s list comprehension syntax to produce
the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90].
"""
print([0, 2, 6, 12, 20, 30, 42, 56, 72, 90])
array = [n * (n+1) for n in range(10)]
print(array)
|
import csv
def print_names():
with open('users.csv') as file:
reader = csv.DictReader(file)
for row in reader:
print("{} {}".format(row['first_name'], row['last_name']))
def add_name():
with open('users.csv', 'a') as file:
fieldnames = ['first_name', 'last_name']
... |
import csv
def use_next():
return print((x for x in range(10)))
|
class Circle:
R = 0
class Reactangle:
A = 0.0
B = 0.0
def Ratio(c : Circle, r:Reactangle) -> bool:
answer = (c.R *2 <= r.A and c.R * 2 <= r.B)
return answer
c = Circle()
c.R = 20
r = Reactangle()
r.A, r.B = 100, 200
print(Ratio(c,r)) |
"""The four adjacent digits in the 1000-digit number that have the greatest product are 9 x 9 x 8 x 9 = 5832.
(num in txt file)
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product.
What is the value of this product?"""
import time
t0 = time.time()
with open('euler8_num.txt') ... |
"""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 = 2**5 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc."""
import time
import math
t0 = time.time()
for a in range(1,1000+1):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.