text stringlengths 37 1.41M |
|---|
#!/usr/bin/python3
""" Rectangle Class """
from models.base import Base
class Rectangle(Base):
""" Rectangle inherits from Base """
def __init__(self, width, height, x=0, y=0, id=None):
""" Init a Rectangle() """
self.width = width
self.height = height
self.x = x
self.... |
print('-'*65)
print('Morbid Predictions Program:')
print()
print('Description: This program asks you for your current age and tells you the year that you will die (on average). ')
print()
age = input('What is your age today? ')
age = int(age)
print('...thinking...')
print('...thinking...')
print('...thinking...')
years... |
mylist = [1, 2, 3, 4, 5, 6]
length = len(mylist)
i = 0
while i < length:
num = mylist[i],
i = i + 1
|
day = raw_input('What day is it? ')
if day == "Friday":
date = int(raw_input('What date is it? '))
if date != 13:
print "TGIF"
else:
print "Ooooo spooky Friday the 13th"
else:
print "Oh no..... zzzzzzzzz"
|
class SinglyLinkedListNode:
""" Node class for singly linked list """
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
""" Singly Linked List Class"""
def __init__(self, values = None):
self.head = None
self.tail = None
def add... |
#Esto es un comentario
#print("Comentario")
print("Hola Mundo!")
print("Adios Muno!")
#Operadores Aritmeticos
5+1
print(4+6)
print(5-2)
print(3*4)
print(20/4)
#precedencia de operadores
print(5+8*(3+2))
#Tipos de datos
print(type(2))
print(type(8.62))
print(type("Texto"))
print(type('Textos'))
print(type("5"))
#Var... |
class Animal(object):
pass
# Dog is a animal, has a name
class Dog(Animal):
def __init__(self, name):
self.name = name
# Cat is a animal, has a name
class Cat(Animal):
def __init__(self, name):
self.name = name
class Person(object):
def __init__(self, name):
self.name = name
self.pet = None
# Employee ... |
class Node():
"""Classe representando um no da implementacao A*"""
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
#g: distancia do no ate o no inicial
self.g = 0
#h: distancia euclidiana do no ate o no final
self.h... |
import random
import timeit
def bubblesort(xs):
swapped = True
while swapped:
swapped = False
# Do a single pass of the list
for i in range(len(xs) - 1):
if xs[i] > xs[i + 1]:
#Swap xs[i] and xs[i+1]
temp = xs[i + 1]
xs[i + 1] =... |
data = [13,0,10,12,1,5,8]
last_spoken = data[-1]
spoken = { v:[i+1] for i,v in enumerate(data) }
for i in range(len(data)+1, 2021):
if (last_spoken in spoken and len(spoken[last_spoken]) > 1):
speak = spoken[last_spoken][-1] - spoken[last_spoken][-2]
else:
speak = 0
#print(speak)
if... |
#!/usr/bin/env python
#
# This script is used for testing tree algorithms.
#
# Liang Wang @ University of Helsinki, Finland
# 2014.09.13
#
import os
import sys
import random
sys.path.append('../code')
def get_random_binary_tree():
from binary_tree import BinaryTree, Node
G = BinaryTree()
G.root = Node(5... |
#!/usr/bin/env python
#
# Different tree algorithms
#
# Liang Wang @ University of Helsinki, Finland
# 2014.09.13
#
import sys
class Node():
left = None
right = None
value = None
def __init__(self, v=None):
self.value = v
pass
class BinaryTree():
root = None
def search(self,... |
print('=== Dasafio 08 ===')
metros = float(input('Digite quantos metros quer converter: '))
print(f'O valor de {metros} metros convertidos: \n centimentos: {metros*100} cm \n milimetros: {metros*1000} mm') |
print('===Desafio 02===')
nome = input('Digite o seu nome: ')
print('Muito prazer em te conhecer {}!'.format(nome))
|
lst=[-2,-1,0,2,3,4]
cnt=1
for i in range(0,len(lst)):
if cnt in lst:
cnt+=1
else:
print(cnt,"is the least positive missing integer")
break
|
employees=[[1001,"ajay","qa",15000],
[1002,"vijay","developer",25000],
[1003,"arun","ba",15000],
[1004,"amal","developer",30000]]
salaryd
salar
for emp in employees:
if(emp[2]=="developer"):
salary+=1
print(salary) |
low=(int(input("enter the lower limit")))
up=(int(input("enter the upper limit")))
odd=0
even=0
for i in range(low,up):
if(i%2==0):
even=even+i
else:
odd=odd+i
print(even,odd) |
#Q.no-> 6
#Finding the number of reps of string 'f' in a given string 's'.
def no_of_reps(txt, pat):
n=len(txt)
m=len(pat)
lps=[0]*m
define_lsp(pat,m , lps)
i=0
j=0
count=0
while i<n:
if pat[j]==txt[i]:
j+=1
i+=1
else:
if j!=0:
... |
import tensorflow as tf
'''
input > weights > hidden layer 1 (activation function) > weights > hidden l2 (activ funct) > weights > output , this does feed forward
compare output to intended output with cost or loss fucntion (cross entopy for exemple)
optimization function/optimizer > minimize cost (AdamOptimize... |
n = int(input("Enter number: "))
m = 3
if n % 2 == 0:
print("Number's minimum divisor is 2")
else:
while m != n:
if n % m == 0:
print("Number minimum divisor is " + str(m))
break
else:
m = m +2
if m == n:
print("Number is Prime number")
... |
__author__ = "Paul Council, Anand Patel"
__version__ = "sprint3"
class MatchData:
"""
Called by TournamentData to track individual matches.
"""
def __init__(self, player1, player2, num_rounds):
"""
:param player1: str
:param player2: str
:param num_rounds: int
"... |
import sys
lineno=0
charno=0
whordno=0
uniquewordno=0
word_set = set()
words = []
path = raw_input("Write input file path: ")
try:
myfile = open(path)
except IOError:
print "The path is not valid. Try again..."
sys.exit()
for line in myfile:
lineno+=1
charno+=len(line)
words = line.split(' ')
whordno+... |
from abc import ABC, abstractmethod
class PieceFactory:
""" Factory to create Piece subclasses. """
@staticmethod
def create(symbol, square):
""" Creates an object depending on the 'symbol' parameter.
Args: symbol (str): character describing the piece.
square (int, i... |
# import dependencies
import os
import csv
# import file
csvpath = 'budget_data.csv'
# read the csv
with open(csvpath, newline='') as csvfile:
# split the data by commas
csvreader = csv.reader(csvfile, delimiter=',')
# define variable
count = 0
total = 0
maxmonth = ''
maxprofit = ... |
def fib(n):
a = 0
b = 1
if n == 1:
print(a)
else:
print(a)
print(b)
for i in range(2,n):
c=a+b
a=b
b=c
print(c)
x= int(input("Enter a non-negative number"))
fib(x)
|
import numpy as np
import matplotlib.pyplot as plt
def estimate_coef(x,y):
n=np.size(x)
m_x,m_y=np.mean(x),np.mean(y)
SS_xy=np.sum(y*x)-n*m_y*m_x
SS_xx=np.sum(x*x)-n*m_x*m_x
b_1=SS_xy/SS_xx
b_0=m_y-b_1*m_x
return(b_0,b_1)
def plot_regression_line(x,y,b):
plt.scatter(x,y,color=... |
import random
m1=int(input("Enter No. of rows in the first matrix: "))
n1=int(input("Enter No. of columns in the first matrix: "))
a = [[random.random() for col in range(n1)] for row in range(m1)]
for i in range(m1):
for j in range(n1):
a[i][j]=input()
m2=int(input ("Enter No. of rows in the second m... |
import cmath
print("\n1. for simple EOQ model \n2. for model with finite production \n3. for model with shortages allowed and are fully backlogged \n4. for generalised model(1+2+3)")
n=int(input("enter the value of n:"))
if(n==4):
A=float(input("Enter per order cost i.e A\n"))
l=float(input("Enter Demand\n... |
from assignments import *
import pandas as pd
#test datetime function
MONTH = "12"
DAY = "31"
YEAR = "2021"
HOUR = "23"
MINUTE = "59"
#should print out Date in YYYY-MM-DD format, then
#Time in HH:MM:SS format, then both combined
duedate_to_datetime(MONTH, DAY, YEAR, HOUR, MINUTE)
loginInfo = pd.read_csv("C:/User... |
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
master = defaultdict(list)
sub_board = defaultdict(list)
for r in range(len(board)):
temp = []
if r%3==0:
sub_board = defaultdict(list)
for c in range(len(board[0])):
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
'''
By padding the inputs, we decide the maximum length of words in a sentence, then zero pads the rest, if the input length
is sharter than the designated length.
'''
csv = 'data/clean_tweet.csv'
my_df = pd.read_c... |
from pyMapReduce import Master, Slave, Job
from threading import Thread
import time
import random
def run_example():
start_port = random.randint(50000, 65000)
def start_slave(port):
slave = Slave(port)
slave.run()
def start_master(port):
master = Master(port)
for i in ran... |
# Example originally based on Python documentation example of using multiprocessing queues
#
# Developed by Jacob Everist, 2019
import asyncio
import multiprocessing
async def run_async_job(sendQueue, recvQueue):
"""
Asynchronous worker that receives tasks and returns results on queues
:param sendQueue: ... |
#3) Create a Python program that uses turtles,
# loops and has at least one user-defined function in it to help draw things.
# It is up to you what the program will do (draw).
import turtle
t = turtle.Turtle()
t.speed(4)
def main():
mapleleaf()
shape()
logo()
def mapleleaf():
t.pencolor("red")
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 17:09:02 2020
@author: Asus
"""
#************************************
# ex1
nums = []
for i in range(2000,3201):
if (i % 7 == 0 and i % 5 !=0):
nums.append(i)
print(nums) |
import statistics
print("你好吖!")
print("""This is a
long line code.""")
x = 10
x += 1
print(x)
lists = []
rap = ["1", "2", "3"]
rock = ["4", "5", "6"]
djs = ["7", "8", "9"]
lists.append(rap)
lists.append(rock)
lists.append(djs)
rap = lists[0]
rap.append("hello")
print(lists)
location = []
la = (12.11, 34.444)
c... |
"""
Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt,
and so on, in a single folder and locates any gaps in the numbering (such as if there is a
spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files
to close this gap.
"""
import os, re
#... |
"""
Create a program multiplicationTable.py that takes a number N from the command line
and creates an N×N multiplication table in an Excel spreadsheet.
"""
import openpyxl, sys
n = int(sys.argv[1]) #converting the CLA into integer
wb = openpyxl.Workbook()
sheet = w... |
"""Write a program that goes to a photo-sharing site like Flickr or Imgur, searches for a
category of photos, and then downloads all the resulting images. You could
write a program that works with any photo site that has a search feature."""
import requests, os, bs4
base_url = "https://imgur.com/search?q=" ... |
#Q.1
def area(r):
a=4*3.14*(r**2)
return a
n=int(input("enter radius: "))
print("area of sphere is : ",area(n))
#Q.2
l=[]
def perfect(n):
p=0
for i in range(1,n):
if n%i==0:
p=p+i
if p==n:
l.append(p)
return l
for j in range(1,1000):
a... |
#excpet
try:
a=int(input("enter number\n"))
if(a>3):
print("b=",a/(a+3))
except:
print("zero error")
except:
print("great")
finally:
print("successful") |
#range
l=[1,'2',"3",4,'gyhj','oi',"iii",8]
for k in range(8):
print(l[k])
l[2]=33
for k in range(8):
print(l[k]) |
def sum(a):
i = 0
for e in a:
i=i+e
return i;
a=[]
n= int(input("number of element in list"))
for k in range(n):
el = int(input("give the elements of list"))
a.append(el)
i = sum(a)
print(i, "is sum of list") |
#rock paper scissors game
#calling random module for choosing a string from tuple using .choice function
import random
a = {"r":"rock", "p":"papers", "s":"scissors"}
m = ["rock", "papers", "scissors"]
w = "you win"
l = "you lose"
u = 0
c = 0
count = 0
#loop to play again and again
while count < 6:
#player will typ... |
import time
#Return current unix time
def currenttime():
return int(time.time())
#returns start and end unix time for peiod given.
def startendtime(minutes):
end=currenttime()
start=end-minutes*60
return start,end
|
import numpy as np
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
m = input('entre the masss:')
key = 'gybnqkurp'
l = []
n = []
for i in range(len(key)):
l.append(alpha.index(key[i]))
print(l)
b = np.array(l)
b.resize(3, 3)... |
import cs50
import csv
from flask import Flask, jsonify, redirect, render_template, request
# Configure application
app = Flask(__name__)
# Reload templates when they are changed
app.config["TEMPLATES_AUTO_RELOAD"] = True
@app.after_request
def after_request(response):
"""Disable caching"""
response.head... |
# 1) Reverse a String and print it on console "Python Skills"
print("\n---Answer 1---")
str="Python Skills"
print("\nOriginal string: ",str)
print("\nReversed string: ",str[::-1])
# 2) Assign String to x variable in DD-MM-YYYY format extract and print Year from String.
print("\n---Answer 2---")
import datetime
date = ... |
'''
You have to write a function pattern which creates the following pattern upto n number of rows.
If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.
If any odd number is passed as argument then the pattern should last upto the largest even number which is smaller than the passed o... |
#Game Board
board = [ "_","_","_",
"_","_","_",
"_","_","_"]
game_still_on = True
position = None
winner = None
#whose turn
current_player = "X"
def display_board():
print(board[0]+"|"+board[1]+"|"+board[2])
print(board[3]+"|"+board[4]+"|"+board[5])
print(board[6]+"|"+board[7]+"|"+board[8])
def pl... |
# def func(lis):
# lis1 = ['Element', 'start', 'finish']
# lis1.insert(2,lis)
# return lis1
# print(func(['hello', 5, 'John', ]))
# # ['Element', 'start', 'hello', 5, 'John', 'finish']
def func(**kwargs):
print(kwargs)
func(x=1, fife=2, John=2)
# {'x':1, 5:2, 'John':3}
# # **kwargs
|
#! /usr/bin/python
# Example page 51 of Chorin
# We want to calculate the mean value using Monte Carlo with and without 'importance sampling'
import random
import math
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
print
def func1(x,N):
valor1 = 0.0
valor1 = (1.0/N) * math.cos... |
age = 18
name = 'zch'
height = 180.0
print('name: %s %d %.1f' % (name, age, height))
print('name: {} {} {}'.format(name, age, height))
if name == 'zch':
print("ok")
else:
print("not")
|
import array
mapa_znakova = {
"a": 1,
"b": 2,
"c": 3,
"d": 1,
"e": 2,
"f": 3,
"g": 1,
"h": 2,
"i": 3,
"j": 1,
"k": 2,
"l": 3,
"m": 1,
"n": 2,
"o": 3,
"p": 1,
"q": 2,
"r": 3,
"s": 4,
"t": 1,
"u": 2,
"v": 3,
"w": 1,
"x": 2,
... |
import re
from word_files import pos_words_dict
from word_files import neg_words_dict
'''Here we will be calculating the number of positive and negative words, percentage of contribution and
also the list of words itself.'''
'''Input Arguments : Cleaned data '''
'''Output : Percentage of Positive words, positiv... |
"""
Little Big Adventure Meta Language Demo
Very simple game engine to interpretate the LBAML
By Rasmus Westerlin, Apps'n Downs, December 2017
General purpose tools
"""
def safeInit(element,default):
if element is None:
return default
return element
def cls():
return
from subprocess impo... |
"""
Top bar displaying information about round
"""
import pygame
class TopBar(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.word = ""
self.round = 1
self.max_round = 8
self.round_... |
import pygame
from button import Button, TextButton
class BottomBar:
COLORS = {
0: (255,255,255),
1: (0,0,0),
2: (255,0,0),
3: (0,255,0),
4: (0,0,255),
5: (255,255,0),
6: (255,140,0),
7: (165,42,42),
8: (128,0,128)
}
def __init__(sel... |
def area_triangle(b, h):
result = 1 / 2 * b * h
print("The area is: ", result)
def area_rectangle(l, w):
result = l * w
print("The area is: ", result)
def area_square(s):
result = s * 2
print("The area is: ", result)
def area_circle(r):
result = 3.14 * r * 2
print("The a... |
import tkinter as tk
from tkinter import *
root = tk.Tk()
root.wm_title("Main") #title of window
root.resizable(width=FALSE,height=FALSE) #Makes the window nonexpandable
myLabel = Label(root,text="My Tool",font="Helvetica 25 bold").pack()
myLabel.place(relx=.2,rely=.1)
def done():
"""Exits the win... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2017/5/9 17:35
import tkinter as tk
class APP(object):
def __init__(self, master):
frame = tk.Frame(master)
# side 设置向哪对齐,pad边界值,x横向,y纵向
frame.pack(side=tk.LEFT, padx=10, pady=10)
self.hi_there = tk.Button(frame, text='how are... |
import function
from tkinter import *
import stringSpacePL
def writeAllAccount():
accountList.delete(0, END)#czyści liste
for accoun in range(function.amountOfAccont()):
# Wczytuje tylko nazwe konta bo w lini zapisana jest nazwa i hasło
accountList.insert(END, function.readAccount(accoun).spli... |
import random
x = random.randint(1, 9)
y = random.randint(1, 9)
z = random.randint(1, 9)
def check_pres_in_array(item, arry):
for i in arry:
if (item == i):
return True
else:
return False
while (y == x):
y = random.randint(1, 9)
while (z == x or z == y):
z = random.randi... |
# -*- coding: utf-8 -*-
"""
AUTHOR:Petrouchka Moise
DESCRIPTION: python text generator
LICENSE:General Public Liscense V2
"""
import random
#List of nouns
nouns = ["brooklyn",
"staten island",
"queens",
"manhattan"]
#List of verbs
verbs = ["yells",
"whispers",
"cries",
... |
import sys
import ast
# Read the elements from the command line
# Strip the first and last character
# Replace the space with nothing
# Split the elements at the first 2 commas
elements = sys.argv[1][1:-1].replace(' ','').split(',', 2)
# Reading the input again to get the board size for output
boardSize = int(element... |
'''
Un codigo resuelve la ecuacion de tirio parabolico
'''
import sys
x0 = float(sys.argv[1])
y0 = float(sys.argv[2])
v0x = float(sys.argv[3])
v0y = float(sys.argv[4])
t0 = int(sys.argv[5])
tf = int(sys.argv[6])
g = 9.81
def x(t):
return x0 + v0x*t
def y(t):
return y0 + v0y*t
for i in range(t0,tf,1):
p... |
"""
Keep a group of sorted elements, navigate new elements to It's position
"""
class InsertionSort:
def __init__(self, l):
self.l = l.copy()
self.n = len(l) - 1
def solve(self):
for m in range(1, self.n + 1):
n = m
while n > 0 and self.l[n - 1] > self.l[n]:
... |
'''
Created on 24 Jul 2014
@author: Lilian
'''
import turtle
my_turtle = turtle.Turtle()
my_turtle.showturtle()
# square size
length = 210
increase = 10
def fill_square(pos_x, pos_y, size, fill_colour):
my_turtle.penup()
my_turtle.goto(pos_x,pos_y)
my_turtle.pendown()
my_turtle.fill(True)
m... |
'''
Created on 20 Jan 2015
@author: lb1008
'''
import abc # library for abstract classes
class AbstractCollection(object):
'''This class provides a skeletal implementation of the Collection interface.'''
__metaclass__ = abc.ABCMeta
def __init__(self):
self._size = 0
@abc.abstract... |
'''
Created on 15 Nov 2016
@author: Lilian
'''
from copy import deepcopy
class Vector(object):
''' Some docs-string to explain the class Vector'''
def __init__(self, data = None):
''' some doc-string to explain how to create an instance of the class
vector'''
self._vector = []
... |
# Ch. 5: Strings
# True / False
# 1. F
# 2. T
# 3. F
# 4. T
# 5. T
# 6. T
# 7. T
# 8. F
# 9. F
# 10. F
#
# Multiple Choice
# 1. D
# 2. C
# 3. A
# 4. C
# 5. C
# 6. D
# 7. D
# 8. C
# 9. C
# 10. A
# Discussion
#1. Show results of the following expressions:
s1 = 'spam'
s2 = 'ni!'
#
# print("The Knights who say, " + s2)
... |
# Ch. 6 - Defining Functions
# True / False
# 1. F
# 2. F
# 3. T
# 4. F
# 5. T #https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference
# 6. F
# 7. F
# 8. T
# 9. T
# 10. F
# Multiple Choice
# 1. B
# 2. A
# 3. A
# 4. B
# 5. D
# 6. A
# 7. D
# 8. A
# 9. D
# 10. A
# Discussion
# 1. 2 motivations... |
'''Question:
Implement an algorithm to find the kth to last element of a singly linked list
clarification:
- what is the Kth to last element? if K is 1, should I return the last element? yes
- should K be positive integers? yes
- what if K is outside of index? return None
- what to return for empty list? None
- can th... |
'''
9.1 You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.
'''
import copy
# clarification questions:
# 1) increasing order? (yes)
# 2) when there is a tie, a goes first? (yes)
# solution:
# merge from the tail but not the... |
'''
9.3
Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originally sorted in increasing order.
EXAMPLE:
Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)
Output: 8 (the index of 5 ... |
'''
You are given an integer K, and a sorted array as an input which has been rotated about an unknown pivot. For example, 4 5 6 7 8 9 1 2 3.
We need to write a function which should return the index of K in the array, if K is present, else return -1.
'''
# clafirication questions:
# 1) for sorted, do you mean it is... |
'''
9.7
A circus is designing a tower routine consisting of people standing atop one another's shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her. Given the heights and weights of each person in the circus, write a method to compute the largest ... |
'''
4.5
Write an algorithm to find the 'next' node (i.e., in-order successor) of a given node in a binary search tree where each node has a link to its parent.
'''
# clarification quesitons:
# 1) so it means thers is a bi-directory link? (yes)
# 2) if there does not exist such next node, return None? (yes)
# 3) a bina... |
'''
The beauty of a number X is the number of 1s in the binary representation of X.
Two players are plaing a game. There is number n written on a black board. The game is played as following:
Each time a player chooses an integer number (0 <= k) so that 2^k is less than n and (n-2^k) has as beautiful as n.
Next he re... |
'''
8.4
Write a method to compute all permutations of a string.
if the method is given the string 'dog' as input,
then it will print out the strings 'god', 'gdo', 'odg', 'ogd', 'dgo', and 'dog'
- since these are all of the possible permutations of the string 'dog'.
Even if a string has characters repeated, each ch... |
# Assignment3a.py: Inserting random data in sqlite
# Page: 79 Book nº2
import sqlite3
import random
with sqlite3.connect('newnum.db') as connection:
c = connection.cursor()
c.executescript("""
DROP TABLE if exists numbers;
CREATE TABLE numbers(num int);
... |
import hashlib
import os
import sqlite3
class AccountNotExists(Exception):
pass
class IncorrectPassword(Exception):
pass
class AccountAlreadyExists(Exception):
pass
class database:
def __init__(self, filename="users.sqlite"):
"""
Initialize db_module object for working with datab... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
"""
1ST STEP: (HARVESTING)
"""
NUM_CUSTOMERS = 20
# time of system
Time = 0
# arrival times with rate of one patient every 2 hour
Arrivals = np.random.exponential(scale=2, size=NUM_CUSTOMERS)
Arrival_times = [np.sum(Arrivals[:n]) for n in range(0, l... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 9 00:34:32 2019
@author: gauravsharma
"""
import random
import numpy as np
import matplotlib.pyplot as plt
# import pandas as pd
#Defining number of patients in one experiment
NUM_PATIENTS = 50
"""cointoss to assign each patient a count to cat... |
class Base:
def hello(self):
print("Hello! I'm base class!")
class Derived(Base):
def hello(self):
print("Hello! I'm derived class!")
b = Base()
d = Derived()
b.hello()
d.hello() |
# libraries to be imported
import re
# loading holmes text file
with open('holmes.txt') as book:
text = book.read()
#####################
# question 1, answer is 461 for specifically 'Holmes'
pattern1 = r'Holmes'
count = len(re.findall(r'\b' + 'Holmes' + r'\b', text))
print(count)
# question 2... |
def reverse_dict(dict):
new_dict = {}
for key, value in dict.items():
new_dict[value] = key
return new_dict
# 영-한 단어장 eng-kor dict
vocab = {
'sanitizer': '살균제',
'ambition': '야망',
'conscience': '양심',
'civilization': '문명',
'privilege': '특권',
'principles': '원칙'
}
# 기존 단어... |
num=int(input("ENTER THE NUMBER:"))
current=0
for i in range(num,0,-1):
current+=1
for j in range(1,i+1):
print(current,end=" ")
print("\r") |
import sqlite3
from sys import argv
###GLOBAL VARIABLES###
db = sqlite3.connect('inventory.db')
c = db.cursor()
contquery = """
To continue type on of the following:
add ~ Add to the amount in inventory
rem ~ Remove from the amount in inventory
set ~ Set the amount in inventory
price ~ Set price of product
ENTER to l... |
"""
# While Loop
# For in --key differences in 'for in' loop clearly defined start and finish to loop
# While--while loops don't stop on a list and has to be told to stop(sentinal value)
"""
# nums = list(range(1,100))
# print(nums)
# ####for in loop
# for num in nums: <--- to print out the list of numbers
# ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
def isPi(s):
pi = "3141592653589793238462643383279502884197169399375105820974944592307816"
l = s.split()
for i in range(len(l)):
if len(l[i]) != int(pi[i]):
return False
return True
T = input()
str = []
for... |
#! /usr/bin/python3
import argparse
# importacion de librerias
def leer_archivo(path):
# path es la ruta del archivo .txt a leer
# ejemplo: "C:/Users/My Folder/sample.txt"
# ejemplo: "/tmp/episodioX.txt"
# fh es nuestra va... |
# -*- coding: utf-8 -*-
'''
pizzas = ["beef","pork","chess","seafood"]
for pizza in pizzas:
print("I like %s pizza" %pizza)
print("I really love pizza")
# 列表解析
# 列表名 = [列表值 列表表达式(for x in xxx)]
for num in range(1,21):
print(num)
lnum = [num for num in range(1,1000001)]
print(max(lnum))
print(min(lnum))
'''
... |
# -*- coding: utf-8 -*
#8-1
def display_message():
print("I am learning functions")
display_message()
# 8-2
def favority_book(book):
print("My favority book is %s" %book)
favority_book(1212)
# 函数参数
# 位置实参、关键字实参、默认值。 默认值实参放在最后。
# 8-3
def make_shirt(size, word="I love python"):
print("\nThe size is %s wi... |
import numpy as np
class Perceptron:
"""A single neuron with the sigmoid activation function.
Attributes:
inputs: The number of inputs in the perceptron, not counting the bias.
bias: The bias term. By defaul it's 1.0."""
def __init__(self, inputs, bias = 1.0):
"""Return a ... |
import torch
from torch import nn, optim
import numpy as np
import matplotlib.pyplot as plt
import random as rdm
class LSTM(nn.Module):
"""
pytorch to define LSTM network
"""
def __init__(self, input_dim, hidden_dim, batch_size, output_dim=1,
num_layers=2):
super(LSTM, s... |
from random import shuffle
def quick_sort(nums):
shuffle(nums)
return quicksort(nums, 0, len(nums) - 1)
def quicksort(nums, low, high):
if low >= high:
return
if high - low < 8:
return insertion_sort(nums, low, high)
pivot_index = partition(nums, low, high)
quicksort(nums, low, ... |
def duplicates(nums):
for num in nums:
if nums[abs(num)] >= 0:
nums[abs(num)] = -nums[abs(num)]
else:
print("Repitition found: ", abs(num))
|
import random, sys;
print("Zahlenraten-Spiel: Bitte geben Sie eine Zahl zwischen 0 und 100 ein")
zufallsZahl = random.randint(0,100)
zahl = None
while zahl != zufallsZahl:
try:
zahl = int(input("Ihre Zahl: "))
if(zahl<=100 and zahl >=0):
if zahl > zufallsZahl: print("Ihre... |
from typing import NewType, Tuple
from iregex import Regex
#: Represents an index in the original string.
OriginalIdx = NewType("OriginalIdx", int)
#: Represents an index in a partial section of the original string.
PartialIdx = NewType("PartialIdx", int)
#: Represents a slice with an inclusive beginning and an exc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.