text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 7 19:48:10 2019
@author: Asher
"""
import numpy as np
from activation_func import ActivationFunction
class Softmax(ActivationFunction):
"""
X of shape NxM where each of the M column vectors is a point of dim Nx1.
W of shape KxN, wher... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 17 14:26:39 2021
@author: Rakesh Kumar
"""
import cv2 as cv
#import matplotlib.pyplot as plt
img_OpenCV=cv.imread('F:\Mastering_OpenCV_from_basics\OpenCV-LearningCurve\images/logo.png')
# Split the loaded image into its three channels (b, g, r):
b ,g ,r=cv.split(img_Ope... |
from pprint import pprint # more control tp print staff and much prettier
# find most repeatative character
sentence = "this is a common interview question"
char_frequency = {}
for char in sentence:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
print(... |
numbers = [1, 2, 3]
print(numbers)
print(1, 2, 3) # print like this =>use * to print individual item like ... in js
print(*numbers)
values = list(range(5))
# or
# unpack any iteralabe like range means take individual values
values2 = [*range(5)]
print(*"hello")
# using in combining the list
first = [1, 2]
second = ... |
class Person:
count = 0
def __init__(self, name, age):
self.name = name
self.age = age
Person.count += 1
def get_name(self):
print("name is %s" % self.name)
def get_age(self):
print("age is %s" % self.age)
def get_info(self):
print("name is %s and ... |
point = {"x": 1, "y": 2}
# or use dict fucntion like tuple () or list ()
point = dict(x=1, y=2)
print(point["x"]) # index is name of key
if "a" in point:
print(point["x"])
print(point.get("a"))
print(point.get("a", 0)) # second argument is default value
del point["x"]
print(point)
# loop over dict
for key ... |
from sys import getsizeof
values = [x * 2 for x in range(10)]
# for x in values:
# print(x)
print(getsizeof(values))
# make generator obj because above is not effiecient when we have lots of data and data set
values2 = (x * 2 for x in range(10))
# it's generaator adn has no len functions
# size of obj?? remain con... |
import pandas as pd #To load in the data
def get_data(path='tryData.csv', cols = ['TV_comm','Sales'], n_rows = 1000):
df = pd.read_csv(path) #Reads in the CSV file specified
df = df[cols] #Gets only the specified columns
df.fillna(0, inplace = True) #Replaces missing values with 0.
arr = df.iloc[:n_row... |
class Quick():
def __init__(self, value = []):
self.value = list(value)
def quickSort(self, L, low, high):
i = low
j = high
if i >= j:
return L
key = L[i]
while i < j:
while i < j and L[j] >= key:
j = j-... |
def vec_select(veclist:list) -> list:
"""
Input: a list called veclist of vectors over the same domain, and an element k of the domain.
Output: the sublist of veclist consisting of the vectors v in veclist where v[k] is zero.
Example: veclist = [0, 1, 2, 3, 4, 5, 0, 9, 1, 3, 0, 3, 0] returns [0, 0, 0... |
def my_filter(L, num):
"""
Input: List of numbers and a positive integer.
Output: List of numbers not containing a multiple of num.
Example: L = [1, 2, 3, 4, 5], num = 2. Return [1, 3, 5]
Return: List
Explanation: l%num produces a remainder. A remainder of l%num cannot be a multiple of num. The... |
def solution(list_of_nums):
e=0
o=0
for i in list_of_nums:
if(i%2==0):
e=e+1
else:
o=o+1
return {'ODD': o, 'EVEN': e}
p=solution([1,2,3,4,5])
print p
|
import datetime as dt
from unittest import TestCase
from src.strategy.emar_due_date_strategy import EmarDueDateStrategy
class TestDueDate(TestCase):
def setUp(self):
self.due_date = EmarDueDateStrategy(9, 17)
self.test_date = dt.datetime(2018, 10, 18, 12, 50)
self.test_turnaround_hours = ... |
"""
A program that takes a letter and outputs a text file of
all of the countries that start with that letter
"""
countries = []
# Read data/countries.txt and save all countries by starting letter
with open("../data/countries.txt") as file: # Remove the ../ if the data folder is a sibling of this file
for line i... |
"""
FizzBuzz is a classic programming challenge.
For every number from 1 to n,
print Fizz if the number is divisible by 3,
print Buzz if the number is divisible by 5,
print FizzBuzz if the number is divisible by 3 and 5,
otherwise, print the original number otherwise
"""
# Simple test helper function
def assert_equa... |
marks=int (input("enter the marks"))
if (marks>90):
print("grade A")
if (marks<60):
print("grade B")
if (marks<50):
print("grade c")
if (marks<40):
print("grade D")
else:
print("fail")
|
import pandas as pd
# Create a Series from a list of values
data = [10, 20, 30, 40, 50]
series = pd.Series(data)
# Print the Series
print(series)
|
'''
Created on Jan 13, 2020
@author: ashish
'''
import numpy as np
a=np.empty([3,2],dtype=int)
print(a)
|
'''
Created on Oct 30, 2019
Linear Regression in Scikit Learn
Reference :https://builtin.com/data-science/supervised-learning-python
@author: asharda
'''
from sklearn import datasets, linear_model
import matplotlib.pyplot as plt
import numpy as np
# Load the diabetes dataset
diabetes = datasets.load_diabetes()
# U... |
'''
Created on Sep 18, 2019
Example using ScikitLearn
@author: asharda
'''
from sklearn.datasets import load_boston
import pandas as pd
boston = load_boston()
boston_data = pd.DataFrame(boston.data, columns=boston.feature_names)
print(boston_data.shape)
print(boston_data.head())
|
import numpy as np
num=np.array([10,2,90,8,12,30])
#Print Min in an array
print("Min number seen is ",np.nanmin(num))
print("Max number is ",np.nanmax(num))
|
'''
Created on Oct 12, 2019
Reverse an array using numpy
@author: asharda
'''
import numpy as np
x=np.array([1,2,3,4,5,])
y=np.flip(x)
print(y)
|
class Employee:
# regular method
# __init__(self) method is a constructor for class
# here self representes the instance
# thats why every method under a class have self argument
def __init__(self, fname, lname, age, email, pay):
self.fname = fname
self.lname = lname
self.a... |
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
if x:
print("YES! We have a match!")
else:
print("No match")
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
prin... |
# 2.Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование строк.
user_time = int (input("Введите время в секундах: "))
hours = user_time//3600
min = (user_time-hours*3600)//60
sec = user_time-hours*3600-min*60
print(f" Время {hour... |
print("This module calculates the largest palindrome in the products of all X digit and Y digit numbers. Enter X and Y")
A = int(input("Enter A>>>"))
B = int(input("Enter B>>>"))
maxnuma = 10**A - 1
minnuma = 10**(A-1) - 1
maxnumb = 10**B - 1
minnumb = 10**(B-1) - 1
palindromelist = []
for y in range(maxnum... |
#Ryan Jones
#2/14/18
#favorites.py
favword = input('Enter your favorite word: ')
favnum = int(input('Enter your favorite number: '))
for i in range(0,(favnum)):
print((favword)) |
def number_guess(num_of_guesses, num):
while(num_of_guesses != 9):
guess = int(input("ENTER THE NUMBER TO GUESS :-\n"))
if guess > num:
num_of_guesses += 1
print("LOWER NUMBER PLEASE!")
print("BE PATIENT, TRY AGAIN!")
print("YOU USED YOUR", num_of_g... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 10:20:18 2020
@author: HP
"""
from random import randint
from time import sleep
preguntar=True
tempo = int()
caracter=str()
lista=[int()for ind3 in range(30)]
while preguntar:
print("Para terminar la ejecución digite 0")
print("Ingresar el tamaño ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 3 12:53:34 2020
@author: HP
"""
def diasHastaFecha(day1, month1, year1, day2, month2, year2):
# Función para calcular si un año es bisiesto o no
def esBisiesto(year):
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
... |
# https://sparkbyexamples.com/pyspark/pyspark-broadcast-variables/
from pyspark.sql.session import SparkSession
spark = SparkSession.builder.appName("RDD Actions").master("local[*]").getOrCreate()
sc = spark.sparkContext
sc.setLogLevel("ERROR")
# Shared Variables
# Broadcast (This is immutable) Use Case : broadcastin... |
from adjacent_digits import (has_adjacent_digits, generate_binary_string,
count_non_adjacent_digits)
import unittest
class test_binary_digits(unittest.TestCase):
def test_adjacent_digits(self):
self.assertFalse(has_adjacent_digits('10'))
self.assertTrue(has_adjacent_dig... |
import re
from pyspark import SparkContext
def split(word):
return [char for char in word]
sparkContext = SparkContext()
sparkContext.setLogLevel('error')
file = sparkContext.textFile("DSBook.txt")
letters = file.flatMap(lambda line: list(line)).filter(lambda letter: letter.isalpha()).map(lambda letter: letter)
... |
n = int(input())
l = input().split(" ")
max = int(l[0])
for i in range(n):
if max < int(l[i]):
max = int(l[i])
print(max)
else:
print(-1) |
s,p =map(str,input().split(" "))
for i in range(len(s)):
if s[i] in p:
s[i].upper()
print(s,end=" ")
print(p) |
n=int(input())
l=input().split()
if n==len(l):
for i in l:
i=sorted(i)
print(i)
|
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = dsquared**0.5
return result
def area(radius):
b = 3.14159 * radius**2
return b
def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return... |
N = input()
# Get the input
numArray = map(int, input().split())
sum_integer = 0
# Write the logic to add these numbers here
sum_integer = sum([x ** 2 for x in numArray])
# Print the sum
print(sum_integer) |
## rename.py ##
## Rename files with .JPG to .jpg ##
#
# Author:
# Mikian Musser - https://github.com/mm909
#
# Usage:
# python rename.py {Path to dir}/*
#
import glob
import os
import sys
print("Active:", str(sys.argv[1]))
images = glob.glob(str(sys.argv[1]))
print("Total Images:", len(images))
count = 0
for f... |
#!/usr/bin/python
import sys
import os
def format(file_name, output_name):
input_file = open(file_name, "r")
output_file = open(output_name, "a+")
for line in input_file:
x = line.split()
name = x[1]
s = ""
is_first = True
for l in name:
if is_first:
... |
people = {
'durval' : {
'first_name': 'Durval',
'last_name': 'pipipopo',
'age': '21',
'city': 'Samanbaia',
},
'hugo' : {
'first_name': 'Hugo',
'last_name': 'Sobral',
'age': '19',
'city': 'Guará',
},
'leo' : {
'first_name': 'Leo',
'last_... |
import math
loop = int(input())
for i in range(0, loop):
number = int(input())
count = 0
for l in range(1, int(math.pow(number, 1/2)) + 1):
if number % l == 0:
count += 1
if count > 1:
break
if count == 1:
print(str(number) + " eh primo")
else:
... |
numero = int(input())
i = 1
while i != numero + 1:
if numero % i == 0:
print(i)
i += 1 |
from optimization import *
def print_solution(sol, dorms, prefs):
slots=[]
# Create two slots for each dorm
for i in range(len(dorms)):
slots+=[i,i]
# Loop over each students assignment
for i in range(len(sol)):
x=int(sol[i])
# Choose the slot from the remaining ones
... |
"""
RSA implementation using Python
Information Security 2
Team : Subin Babu & Kalyani More
"""
import copy
import random
def gen_primes(digit):
# type: (object) -> object
first_number = random.randint(10 ** (digit - 1), 10 ** digit)
if first_number % 2 == 0:
first_number += 1
p = get_prime(f... |
# https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm
def selection_sort(input_list):
for idx in range(len(input_list)):
min_idx = idx
for j in range( idx +1, len(input_list)):
if input_list[min_idx] > input_list[j]:
min_idx = j
inp... |
num1=input().split()
for x in num1:
s=set(x)
if leng(s) == leng(x):
print("Yes")
else:
print("No")
|
''' QUESTION:
Anti Corona Serum :
Corona, a deadly virus, which created a global impact in the year 2020. Thousands of people died because of it.
A doctor called Victor from India who finally created a serum for curing it. After 1000 years, we are now at 3020, corona is beginning to become a global threat.
On... |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.36
工具: python == 3.7.3
"""
def quick_sort(nums, left, right):
if left >= right:
return -1
i = left
j = right
mid = nums[(left + right) >> 1]
while i < j:
while nums[i] < mid:
i +... |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.35.1
工具: python == 3.7.3
任务: 新购买的餐桌无法及时送达,因此只能邀请两位嘉宾
以03_Add_Guest_List为基础
1. 在程序末尾添加一行代码,打印一条你只能邀请两位嘉宾共进晚餐的消息
2. 使用pop()不断地删除名单中的嘉宾,直到只有两位嘉宾为止
每次从名单中弹出一位嘉宾时,都打印一条消息,让该嘉宾知悉你很抱歉,无法邀请他来共进晚餐
... |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.35.1
工具: python == 3.7.3
任务: 利用列表生成数字
"""
"""
创建一个列表,其中包含3~30能被3整除的数
再使用一个for循环将这个列表中的数字都打印出来
"""
numbers = list(range(3, 31, 3))
for number in numbers:
print(number)
"""
创建一个列表,其中包含前10个整数(即1~10)的立方
再使用一个for循环将这些立方数都打印出... |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.35.1
工具: python == 3.7.3
任务: 创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键-值对可能是'nile': 'egypt'
1. 使用循环为每条河流打印一条消息,如The Nile runs through Egypt
2. 使用循环将该字典中每条河流的名字都打印出来
3. 使用循环将该字典包含的每个国家的名字都打印出来
"""
rivers = {
'... |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code
工具: python3
"""
"""
实验5-2:幂级数,e^x = 1 + x + x^2 / 2! + x^3 / 3! + ... + x^n / n! (0 < x < 1)
"""
#!/usr/bin/env python3
x = float(input("Enter the value of x: "))
n = term = num = 1
result = 1.0
while n <= 100:
term *= x / n... |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.35.1
工具: python == 3.7.3
任务: 在06_Admin的基础上
1. 编写一个名为Privileges的类,它只有一个属性privileges,其中存储了06_Admin的字符串列表
2. 将方法show_privileges()移到这个类中
3. 在Admin类中,将一个Privileges实例用作其属性
4. 创建一个Admin实例,并使用方法show_pri... |
"""Масиви"""
def transpose(matrix):
a = []
for i in range(len(matrix[0])):
b = []
for row in matrix:
b.append(row[i])
a.append(b)
return a
B = [[1.0,2.0,3.0],
[4.0,5.0,6.0],
[7.0,8.0,9.0]]
C = transpose(B)
print("C:", C)
print("B:", B)
def small(list): #list o... |
from tkinter import *
from tkinter import messagebox
import sqlite3
import os
class MyProj:
def CancelTik(self):
print(self.password.get())
with sqlite3.connect('TrainTicketBooking.db') as db:
c = db.cursor()
c.execute('SELECT * FROM Temp where key == 2')
temp... |
import prompt
QUESTION_TRIES_NUMBER = 3
def welcome_user():
print('Welcome to the Brain Games!')
name = prompt.string('May I have your name? ')
print('Hello, {}!'.format(name))
return name
def show_and_handle_questions(
get_correct_answer_func,
get_question_value_func,
us... |
#TASK 1
#Hash Program
#function to
def hashString(str):
h = 7
letters = 'acdegilmnoprstuw' #refernce string
for alphabet in str:
h = (h * 37 + letters.index(alphabet)) #compute hash
return h #Return the hash value
#call to the hashString Function
hString = hashString('leepadg')
print(hString... |
# CS5 Gold, Lab1 part 2
# Filename: hw1pr2.py
# Name: Lawrence
# Problem description: First few functions!
from math import *
def dbl(x):
"""
output: dbl returns twice its input
input x: a number (int or float)
Spam is great, and dbl("spam") is better!
"""
return ... |
def fortytwo(number):
if number == 0:
return
else:
#Creating 4
down()
right(90)
forward(10)
left(90)
forward(15)
left(90)
forward(10)
backward(20)
up()
right(90)
forward (3)
#C... |
#
# hw6pr5.py - Intro to loops!
#
# Name: Lawrence Mao
#
import random
def countGuesses( hidden ):
"""
uses a while loop to guess hidden, from 0 to 99
input: hidden, a "hidden" integer from 0 to 99
output: the number of guesses needed to guess hidden
"""
guess = random.choice( ran... |
# CS5 Gold, hw1pr3
# Filename: hw1pr3.py
# Name: Lawrence Mao
# Problem description: Function Frenzy!
#
# leng example from class
#
def leng( s ):
""" leng outputs the length of s
input: s, which can be a string or list
"""
if s == '' or s == []: # if empty string or empty lis... |
print("enter the no. of elements:")
n = int(input())
print("enter the elements one after other separated by space:")
a = list(map(int,input().split()))
for i in range(1,n):
key = a[i]
j = i-1
while j>=0 and a[j]>key:
a[j+1] = a[j]
j = j-1
a[j+1] = key
print("Sorted Array i... |
import os
import shutil
#writing the name of directory here that needs to get sorted and providing the path
path = input("enter the name of the directory to be sorted:-")
#this is will create a properly organized list with all the file names that are in the directory
list_of_files = os.listdir(path)
#this will go... |
#create a musician class
# first atrributes will be name and genre
# other attributes: instrument, years active, top hit, number of albums
class Musician(object):
"""A class that creates musicians"""
def __init__ (self, name, genre, top_hit, is_on_tour): # self = object calling, the name of the object itself
... |
import re
string = 'xixi gq bhbx'
print(re.search(r'^bonito', string)) # show where the word start and finish
print(re.findall(r'bonito', string))
print(re.sub('bonito','feio',string))
################### the other manner
print(re.search(r'^x.*', string)) |
# _*_ coding:utf-8 _*_
import re
def modify_contact():
name = input('----------------------\nWhich contact you want to modify?(Name):')
if name == '':
print('----------------------\nName is empty')
modify_contact()
else:
try:
with open(r'.\contact.txt', 'r') as f:
... |
#!/bin/python3
import sys
def find(word1, word2):
base_list = [0 for i in range(26)]
for i in word2:
base_list[ord(i) % 26] += 1
for i in word1:
if base_list[ord(i) % 26] > 0:
print("YES")
return
print("NO")
cases = int(input().strip())
for case in range(cas... |
print("Enter the size of the list:")
N = int(input())
the_list=[]
# for x in range(N):
# x = input("")
# the_list.append(x)
# the_list.sort()
# print(the_list)
for x in range(N):
x = input("Enter elements: ")
try:
the_list.append(int(x))
except ValueError:
the_list.append... |
l=[]
n=int(input("Enter Limit: "))
for i in range(0,n):
a=int(input("Enter Elements: "))
l.append(a)
s1=0
s2=0
s3=0
for j in l:
if(j>0):
if(j%2==0):
s1=s1+j
else:
s2=s2+j
else:
s3=s3+j
print("Sum of all positive even numbersq:",s1)
print("Sum of all positive odd numbers:",s2)
print("Sum o... |
a=[]
b=[]
n=int(input("Enter length: "))
print("\n")
for i in range(0,n):
ele=int(input("Enter numbers: "))
a.append(ele)
print("\nThe squared tuples are")
for j in a:
a=[(j,j**2)]
print(a) |
from stackType_01 import Stack
from binaryTree_20 import BinaryTree
def build_parse_tree(fp_exp):
fp_list = fp_exp.split()
p_stack = Stack()
e_tree = BinaryTree('')
p_stack.push(e_tree)
current_tree = e_tree
for i in fp_list:
if i == '(':
current_tree.insert_left('')
... |
class Deque: # right is the front
def __init__(self,*args):
self.item = []
for i in args:
self.item.insert(0,i)
def __len__(self):
return len(self.item)
def size(self):
return len(self.item)
def is_empty(self):
if self.size() == 0:... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 16:15:05 2016
@author: srowe
"""
# So-called "proper" divisors are numbers less than n that
# divide n evenly.
factor_cache = dict()
def proper_divisors(n):
if factor_cache.has_key(n):
return factor_cache.get(n)
rc = set([1])
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 07:46:56 2016
@author: Steve
"""
#
# Generate all right triangles of perimeter p
# p = a + b + c
# c*c = a*a + b*b
def sides(p):
rc = []
for a in range(1, p-1):
for b in range(a, p-1):
c = p - b - a
if c <= 0 or (a... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 14:34:12 2016
@author: srowe
"""
month_names = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
def days_in_month(month, year):
days_per_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month != 1:
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 18:06:30 2016
@author: srowe
"""
primes = [2,3]
def is_prime(n):
for p in primes:
if n % p == 0:
return False
return True
def more_primes(n):
c = primes[-1]+1
while len(primes) < n:
if i... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 18:32:37 2016
@author: srowe
"""
def is_pythagorean_triplet(a,b,c):
return a*a + b*b == c*c
def sum_to_1000(a,b,c):
return a+b+c == 1000
def do_eet():
for a in range(1,1001):
for b in range(1,1001):
for c in ra... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 7 01:22:59 2021
@author: vignesh jaishankar
"""
from random import random
from time import clock
randVal = random()
#print(randVal)
upper = 1.0
lower = 0.0
#guess = 0.5
startTime = clock()
while(True):
guess = (lower+upper)/2
if ... |
from bs4 import BeautifulSoup
SIMPLE_HTML = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SIMPLE_HTML</title>
</head>
<body>
<h1>This is the title</h1>
<p class="subtitle">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque dolore doloremque hic magnam, nam nost... |
"""
Advent of Code 2019: Day 5
"""
from typing import List, Dict, Set
class Orbit:
"""
Represents an orbit
"""
def __init__(self, name: str):
self.name: str = name
self.root: bool = True
self.children: List[Orbit] = []
def __str__(self) -> str:
return_string = "{}... |
#Q.3- Create a class Cop. Initialize its name, age , work experience and designation. Define methods to add, display and update the following details. Create another class Mission which extends the class Cop. Define method add_mission _details. Select an object of Cop and access methods of base class to get information... |
class Person(object):
def __init__(self, person_id, first_name, last_name, designation):
self.Id = person_id
self.name = first_name + " " + last_name
self.designation = designation
class Fellow(Person):
def __init__(self, person_id, first_name, last_name, designation):
super(Fe... |
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> l1=[2,3,4,5]
>>> def add(l1):
l1.append(6)
print(l1)
>>> add(l1)
[2, 3, 4, 5, 6]
>>> l2=[2,3,4,5]
>>> def dele(l2):
l2.pop(2)
prin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Viola Fanfani
### WELCOME TO THE FIRST LAB ####
"""
## Data Types
#%%
"""
Examples 1: a few operations with numbers and strings
"""
# A school has 3 classrooms, each of them can contain 20 students.
# How many students can be enrolled in the school?
n_clas... |
import streamlit as st
import altair as alt
import numpy as np
import pandas as pd
# import time
from stock_database import Database
class Application:
def __init__(self):
db = Database()
df = db.return_contents()
df_names = pd.read_csv('../data_fetch/robinhood_data/100_most_popular_nam... |
'''import numpy as np
import csv
def csv2math(filename):
return np.array(list(csv.reader(open(filename,"rt"),delimiter=",")))
A=csv2math('A.csv') #อ่านไฟล์
b=csv2math('b.csv')'''
def readm(fname='A.csv'):
f = open(fname,'r')#w,b
A = []
for line in f.readlines():
A.append([float(x) for x in li... |
#NOT WORKING
def same_sign(a, b):
return a*b > 0
def incremental_searches(f, value, delta):
xnew = value + delta
#assert not same_sign(f(value), f(xnew))
for i in range(54):
if same_sign:
value = xnew
xnew = value + delta
else:
print("["+ value , xn... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 18 15:44:49 2020
@author: anwar
"""
# Fibonacci with a Dictionary
def fib_efficient(n, d):
if n in d:
return d[n]
else:
ans = fib_efficient(n-1, d) + fib_efficient(n-2,d)
d[n] = ans
return ans
d = {1:1, 2:2}
... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
x = np.array([[1,1],[1, 0],[0,1],[0, 0]])
y = np.array([[0],[1],[1],[0]])
# making model 모델 만들기
model = tf.keras.Sequential([
# 노드 두개 activation function=sigmoid, input_shpae
tf.keras.layers.Dense(units=3, acti... |
# Copyright (C) 2013 Lars Wirzenius
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed i... |
#! /Users/user/.pyenv/versions/3.7.5/bin/python3
# strongPasswordDectection: checks whether
# a copied password or entered password is strong.
import re
import time
import pyperclip
def main():
# built a function that uses REGEX to make sure the password string it is passed
# is at least 8 characters long... |
"""Advent of Code 2017 Day 5: A Maze of Twisty Trampolines, All Alike"""
import helper
def jump(jumps, offset):
"""Given jump array and offset function, compute number of jumps."""
jumps = jumps.copy() # Copy to avoid modifying list
idx = 0 # current location
prev = 0 # previous location
count... |
import helper
import itertools
def reverse_cycle(lst, start, end):
"""Reverses part of a circular list in-place.
Ex: [0,1,2,(3,4][0,1),2,3,4] -> [...2,(1,0][4,3),2...]"""
N = len(lst)
# Select the part of the cycle to reverse
group = itertools.islice(itertools.cycle(lst[:]), start, end)
# Rever... |
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'. """
def test_first_last_name(self):
"""Do names like 'Janis Joplin' work?"""
formatted_name = get_formatted_name('lawal', 'john')
self.assertEqual(formatt... |
import sys
# Try to read the file and separeted into lines
def read(input):
try:
with open(input, "r") as file:
lines = {}
for i, l in enumerate(file):
lines[i + 1] = l
# Check if the file is empty
if len(lines) == 0:
print("There is no... |
import calendar
# yy = 2014
# mm = 11
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))
|
class Link:
def __init__(self, value):
self.value = value
self.next = None
self.previous = None
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.__first = None
def insert(self, value):
link = Link(value)
li... |
# NLTK is our Natural-Language-Took-Kit
import re
import string
import nltk
from nltk.corpus import wordnet
from nltk.stem import WordNetLemmatizer
from nltk.stem import PorterStemmer
from nltk import word_tokenize
from nltk.corpus import stopwords
stopwords = stopwords.words('english')
# Libraries for helping us with... |
# Day 1
"""
Code Challenge
Name:
Replacing of Characters
Filename:
restart.py
Problem Statement:
In a hardcoded string RESTART, replace all the R with $
except the first occurrence and print it.
Input:
RESTART
Output:
RESTA$T
"""
str1 = "RESTART" #Hardcoding str1
# Below to fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.