text stringlengths 37 1.41M |
|---|
# Ian Cowan
# Apr 1 2019
# Problem 12 on page 368
# Pig Latin Translator
# Define convertToPig()
# Inputs:
# str: eng
# Outputs:
# str: pig
def convertToPig(eng):
# Split up the words, init variables
words = eng.split()
pig = list()
# Loop through each word and convert it to pig latin
for w in... |
# Ian Cowan
# Feb 25 2019
# Problem 3 on page 161
# Budget Analysis
# Prompts the user for their monthly budget
bud = float(input('What is your budget for this month? $'))
# Initialize variables for Loop
print('Enter the cost of each of your expenses for the month. Press "enter" when you\'re finished.')
spend = input... |
# Ian Cowan
# Feb 18 2019
# Problem 4 on page 162
# Distance Traveled
# Prompts the user to input the speed (in mph) and hours of travel
mph = int(input('What is the speed of the vehicle in mph? '))
hours = int(input('How many hours has the vehicle been traveling? '))
# Adds the headers to the table
print('')
print('... |
# Ian Cowan
# Apr 3 2019
# Problem 3 on page 416
# File Encryption and Decryption
# Define loadEncryption()
# Inputs:
# str: file_name
# str: cryption
# Outputs:
# dict: encryption
def loadEncryption(file_name, cryption):
# Open the file
file_in = open(file_name, 'r')
# Init variables
encryption... |
# Ian Cowan
# Lab Partner: Jake Pfaller
# CSC 117b Lab16 File IO 1
# 11 Mar 2019
# Define step1()
# Inputs:
# NONE
# Outputs:
# NONE
def step1():
# Open people.txt for writing
file_out = open('people.txt', 'w')
# Prompt the user for the first name
name = input('Enter name ("DONE" to finish): '... |
# Ian Cowan
# Lab Partner: Jake Pfaller
# CSC 117b Lab26 OOPS 2
# 17 Apr 2019
# ITEM CLASS
# Item
# Attributes:
# String __name
# float __price
# String __itemType
# int __quantity
# Methods:
# String getName()
# float getPrice()
# String getType()
# int getQuantity()
# void setName(String)
# void ... |
# Ian Cowan
# Lab Partner: Jake Pfaller
# CSC 117b Lab09 Loops2
# 20 Feb 2019
# Imports
import random
# Begin Average
# Prompt the user for the first score and initialize accumulator/index
new_score = int(input('Enter score: '))
score = 0
i = 0
while new_score >= 0 and new_score <= 100:
score += new_score
new... |
# Ian Cowan
# Lab Partner: Jake Pfaller
# CSC 117b Lab26 OOPS 2
# 17 Apr 2019
# MAIN
# Import Classes
from Customer import Customer
from Item import Item
# Define initCustomersItems()
# Inputs:
# NONE
# Outputs:
# dict[String customerName : Customer] customers
# dict[String itemName : Item] items
def initCustom... |
# Ian Cowan
# CSC 117b Lab12 Graphics Warmup
# 27 Feb 2019
# Import Packages
from graphics import *
import time
# Graphics warmup!
print('Graphics warmup!')
# Set parameters of graphics window
windowWidth = 400
windowHeight = 400
windowTitle = 'My Cool Window'
# Create the window by instantiating the GraphWin class... |
numero_tabla = int(input("Introduce el numero del cual quieres sacar la tabla: "))
numero_min = int(input("Introduce el numero desde el cual quieres empezar: "))
numero_max = int(input("Introduce el numero desde el cual quieres terminar: "))
for numero in range(numero_min,numero_max+1):
print("{} * {} = {}".fo... |
frase_usuario = input("Escriba la frases para contar las mayusculas: ")
mayusculas = "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"
mayusculas_cuenta = 0
for lestras in frase_usuario:
if lestras in mayusculas:
mayusculas_cuenta += 1
print("Tu fras... |
theString = "Hello "
theString2 = "World!"
theString3 = theString + theString2
print(theString3) |
"""
Question A
Your goal for this question is to write a program that accepts two lines (x1,x2) and (x3,x4) on the x-axis and returns whether they overlap.
As an example, (1,5) and (2,6) overlaps but not (1,5) and (6,8).
"""
def ifOverlap(x1, x2, x3, x4):
try:
x = range(x1, x2)
y = range(x3, x4)
xs = set(x... |
def printLevel(m, tR, tC, dR, dC, toDown):
if toDown:
while tR != dR + 1:
print(m[tR][tC], end=' ')
tR += 1
tC -= 1
else:
while dR != tR - 1:
print(m[dR][dC], end=' ')
dR -= 1
dC += 1
def zigzagPrintMatrix(matrix):
tR, tC = 0, 0
dR, dC = 0, 0
endR, endC = len(matrix)-1, len(matrix[0])-1
to... |
"""并查集"""
class Data(object):
"""数据的类型与结构(支持任何类型)
"""
class unionFindSets(object):
"""并查集类
"""
def __init__(self):
"""初始化结构"""
self.fatherMap = dict()
self.sizeMap = dict()
def makeSets(self, datas):
"""初始化并查集
"""
self.fatherMap.clear()
self.sizeMap.clear()
for each in datas:
self.fatherMap[... |
"""给定二叉树的头结点head,判断这棵二叉树是否为平衡二叉树
平衡二叉树的性质:
要么是空树
要么任何一个节点的左右子树高度差的绝对值不超过1
"""
def isBalance(head):
"""判断以head为头的树是否为平衡二叉树
"""
if head == None: return True
isB, height = posOrder(head, 1)
return isB
def posOrder(node, level):
"""返回两个信息 是否是平衡二叉树、最深到哪一层
node 表示 头结点; level 表示 当前头结点所在的层数
"""
if node == None... |
"""寻找两个单链表相交的第一个结点的问题"""
def getIntersectNode(head1, head2):
"""分三种情况:
1. 都无环
2. 都有有环
3. 一个有环一个无环
"""
if head1 == None or head2 == None: return None
loop1 = getLoopNode(head1)
loop2 = getLoopNode(head2)
if loop1 == None and loop2 == None:
return noLoop(head1, head2)
if loop1 != None and loop2 != None... |
"""给定一个数组arr 和 一整数w代表窗口大小。窗口从数组的最左侧滑向最右侧,每次仅向右滑动一个位置,
返回一个长度为 n-w+1的数组res,res[i]表示每一种窗口状态下的最大值"""
def getArrayOfMAX(arr, w):
if arr == None or len(arr) == 0 or w < 1 or w > len(arr):
return None
res = []
qmax = []
for i in range(len(arr)):
while len(qmax) != 0 and arr[qmax[-1]] <= arr[i]:
qmax.pop(-1)
... |
"""给定一个长度为N的整型数组arr,可以将其划分成左右两部分arr[0···k], arr[k+1···N-1]
k的取值是[0, n-2),求这些划分中方案中,左部分最大-右部分最大的绝对值中的最大值。
"""
def maxAbs1(arr):
"""预处理数组法
时间复杂度O(n),额外空间O(N)
"""
if arr == None or len(arr) == 0:
return 0
length = len(arr)
lmax, rmax = [0] * length, [0] * length
lmax[0] = arr[0]
rmax[length-1] = arr[length-... |
"""打印一个字符串所有子序列(不改变次序)"""
def printAllSubSequence(string):
if string == None:
return None
process(string, 0, "")
def process(string, index, pre):
if index == len(string):
if pre != "":
print(pre)
return None
process(string, index + 1, pre + string[index])
process(string, index + 1, pre)
if __name__... |
"""给定一颗二叉树的头结点head,已知其中所有节点的值都不一样,找到含有节点数最多的搜索二叉树,
并返回这颗子树的头结点。
要求: 时间复杂度 O(N),额外空间复杂度O(h)"""
def biggestSubBST(head):
return posOrder(head)[0]
def posOrder(head):
"""返回四个信息
最大搜索二叉树:头结点、 节点数、 最小值、 最大值
"""
if head == None:
return None, 0, float('inf'), float('-inf')
lBST, lSize, lMin, lMax = posOrder(head... |
"""找到有序数组中第一个大于或等于k的数"""
def findNumberIndex(arr, target):
"""二分找数"""
if arr == None or len(arr) == 0:
return -1
l, r = 0, len(arr) - 1
res = -1
while r > l:
mid = l + ((r-l)>>1)
if arr[mid] >= target:
r = mid - 1
res = mid if arr[mid] == target else res
else:
l = mid + 1
return l if arr[l] ==... |
def insert_sort(li):
for i in range(1, len(li)):
j = i - 1
temp = li[i]
while j >= 0 and li[j] > temp:
li[j + 1] = li[j]
j -= 1
li[j + 1] = temp
li = [1, 20, 23, 42, 21, 19, 10, 13]
insert_sort(li)
print(li)
|
#Creamos una matriz
matriz1 = [[1, 2, 3, 4], [-5, 6, 7, 8], [9, 0, 1, 2]]
print("Matriz 1: \n", matriz1, "\n")
matriz2 = [[3, 4, 5, 6], [7, 8, 9, 0], [1, 2, 3, -4]]
print("Matriz 2: \n", matriz2, "\n")
#Realizamos una operación entre las matrices
suma1 = matriz1 + matriz2
print("La suma de lasdos matrices es: \n", sum... |
max=0
now=0
for i in range(9):
a=int(input())
if a>max:
max=a
now=i+1
print(max)
print(now) |
print('…………我的…………')
temp = input("猜猜现在我想到的是哪个数字:")
guess = int(temp)
if guess == 6:
print("对了")
print("对了就对了吧")
else :
print("猜错了")
print("不玩了")
|
def fbnq(n):
n1 = 1
n2 = 1
n3 = 1
if n < 1:
print("输入有误!")
return -1
while (n-2) > 0:
n3 = n1 + n2
n1 = n2
n2 = n3
n -= 1
return n3
num = int(input("欲计算的斐波那契数列的第几位数:"))
result = fbnq(num)
if result != -1:
print("斐波那契数列的第%d个数字是:%d" % (num , r... |
multipleSum = 0
x = 1
while x < 1000:
if x % 3 == 0 or x % 5 == 0:
multipleSum += x
x += 1
print multipleSum
|
""" sound.py: Contains the Sound class. """
import os
import config
class Sound:
""" A class for the audio component of the game. Audio file locations
are defined in the config file. """
def __init__(self, pygame):
""" Initialise and load audio.
__init__(pygame) -> v... |
""" omino.py: Contains the Omino class. """
import random
import copy
import math
from helpers import *
class Omino:
""" A class representing a single polyomino. """
def __init__(self, shape, colour, rotation=None):
""" Create a new omino. Shape is a square 2D list filled with boolean
... |
#reference: the bulk of this code is adopted from Prof. Panos' Machine Learning 2 course teaching materials
from pyspark.ml.recommendation import ALS
from pyspark.sql import Row
import pandas as pd
df = spark.read.load("data/final1.csv", format = 'csv', header = 'true')
df2 = df.withColumn("tot", df["tot"].cast("do... |
smallest = None
biggest = None
while True:
prompt = input('Enter a number: ')
if prompt == 'done' :
break
try:
digit = float(prompt)
except:
print('Invalid input')
continue
if biggest is None :
biggest = digit
elif biggest < digit :
... |
import abc as abc
import pygame as pg
from field import Field
import colors
import pygame.freetype
import utils
class Button(Field):
"""
Parent class to all icons and other clickable, rectangular objects. Subclass of Field class.
Attributes (for other attributes see Field):
is_pressed (bool)
... |
# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8') # python的str默认是ascii编码,和unicode编码冲突,需要加上这几句
# 二、栈:概念和实现
# 基于顺序表实现一个栈(表尾作为栈顶)
class StackUnderflow(ValueError): # 定义一个异常:栈下溢(空栈访问)
pass
class SStack():
def __init__(self): # 用list对象 _elems存储栈中元素
self._elems = [] # 所有栈操作都映射到l... |
import sys
import re
pattern = re.compile(r'(\d+)-(\d+) ([a-z]+): ([a-z]+)')
valid_a = 0
valid_b = 0
for line in open(sys.argv[1]).readlines():
m = pattern.match(line.strip())
[low, high, ch, password] = m.groups()
# Wow - this is 100% the wrong way to do this!
# This code finds all the ones... |
#Use pandas to load chicago.csv into a dataframe, and find the most frequent hour when people start traveling. There isn't an hour column in this dataset, but you can create one by extracting the hour from the "Start Time" column. To do this, you can convert "Start Time" to the datetime datatype using the pandas to_dat... |
# Implement a program that identifies a person based on their DNA, per the below.
# The program should require as its first command-line argument the name of
# a CSV file containing the STR counts for a list of individuals and should require
# as its second command-line argument the name of a text file containing the
... |
# Implement a program that determines whether a provided credit card number is valid according to Luhn’s algorithm. #
def main():
# Propt user for number #
number = input("Number: ")
try:
val = int(number)
# Check if its a number #
except ValueError:
print("INVALID\n")
retu... |
# -*- coding: utf-8 -*-
"""
Create a GUI to import a CSV file into Python
"""
import tkinter as tk
from tkinter import filedialog
import pandas as pd
root=tk.Tk()
canvas1=tk.Canvas(root, width=300, height=300, bg='lightsteelblue2', relief='raised')
canvas1.pack()
def getCSV():
global df
... |
'''
Curso: Engenharia Elétrica
Disciplina: Sistemas Inteligentes
Professor: Carlos Roberto Jr
Título: Algoritmo do perceptron para duas entradas
Observações:
Aprender uma lógica OR para o algoritmo é mais fácil do que aprender uma lógica AND.
Nos testes com logica AND são muitas iterações e não obtem um MSE satisfa... |
"""
gap:差額
position:位置
target:目標
判斷gap是否有出現過, 有的話回傳
存判斷過的值與該值的位置, value:position
過程:
arr = [1, 3, 4, 8, 10]
target = 13
======================
i = 0
m = {} bf
arr[i] = 1
gap = 12
m = {1: 0} af
======================
i = 1
m = {1: 0} bf
arr[i] = 3
gap = 10
m = {1:... |
"""
找出最長的前綴
Input: ['flower','flow','flight']
Output: 'fl'
Input: ['dog','racecar','car']
Output: ''
思路
A=Input
先找出長度最小字串, shortest_str
回圈shortest_str:
回圈A:
如A[i]==shortest_str[i]下一圈(不寫)
A[i]!=shortest_str[i]回傳shortest_str[0:i](不含i)
"""
def solve(A):
if len(A) == 0:
return ''
#... |
"""
求出最小的絕對值
P將整個A切兩等份
求出這兩等份個別加總後取絕對值
0 < P < N
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7
思路
從i = 0開始
l=0 左半邊加總(先加出來)
r=sum(A) 右半邊加總(先加出來)
m = abs(l - r) 最小值
回圈A 從i=1開始:
l += A[i... |
"""
輸出最長連續的路徑的長度
"""
class Node:
def __init__(self, val, l, r):
self.val = val
self.l = l
self.r = r
def get1():
"""
1
\
3
/ \
6 4
\
5
"""
n5 = Node(5, None, Non... |
"""
鏡射二元樹
"""
from traversal import print_tree
class Node:
def __init__(self, val, l, r):
self.val = val
self.l = l
self.r = r
def get():
"""
1
/ \
2 3
/ \ / \
4 5 6 7
"""
n4 = Node(4, None, None)
n5 = Node(... |
# _*_ coding: utf-8 -*-
# @Time : 8/26/20 3:26 PM
# @Author : title_z
# @Filename : InsertionSort.py
def insertionsort(alist):
for index in range(1, len(alist)):
# 插入新项
currentvalue = alist[index]
position = index
while position > 0 and alist[position - 1] > currentvalue: ... |
import random
play_again = 'Y'
while(play_again == 'Y'):
random_integer = random.randint(1, 100)
int(random_integer)
print(random_integer)
print("Guess an integer between One and 100: \n")
guess = 0
while(int(guess) != random_integer):
guess = input("Enter Your Guess: ")
if(... |
a = list(int(input("Write your first list through a space: ")))
b = list(int(input("Write your second list through a space: ")))
print(a)
print(b)
|
def calculating(x):
calculate = 1
for i in range(1, x):
if i % 2 != 0:
calculate *= i
return calculate
num = int(input("Write your x: "))
calculating(num)
|
import random
def prak1():
lst = list(map(int, input("Write your list of integer numbers through a comma: ").split(",")))
print("Your list is:", lst)
def prak2():
lst = list(input("Write you list: "))
print("Your first element in list is '{}' and last element is '{}'".format(lst[0], lst[-1]))
def ... |
#Write a Python program to combine two dictionary adding values for common keys.
d1={'a':100,'b':200,'c':300}
d2={'a':300,'b':200,'d':400}
counter={}
for key,x in d1.items():
if key in d2:
d1[key]=x+d2[key]
del d2[key]
d1.update(d2)
print(d1) |
pets = ['cats', 'dogs', 'hamster', 'tortoise']
for myPets in pets:
print(myPets)
pets.append('rabbit')
for index, myPets in enumerate(pets):
print(index, myPets)
age = {'Peter': 55, 'Jon': 30}
for i in age:
print(i) # Prints off only Peter and Jon
for i in age:
print("%s is %d years old" % (i, age... |
def fact():
n=int(input('enter the given number to find fact'))
fact=1
for i in range(1,n+1):
fact=fact*i
print(fact,end="")
fact()
def get(*a):
print(a)
get(10,20,30)
def get(**a):
print(a)
get(ashwini='10',raj='10',ash='12')
n = 2
fact = 1
for i in range(1,n+1):
fact = fact * ... |
numbers=('12345')
d=len(numbers)
if(d%2)==0:
print('i am even',numbers[:2],numbers[-2:])
else:
n=(int(len(numbers)/2))
print(numbers[:2],numbers[n],numbers[-2:])
|
n=int(input('enter'))
for i in range(0, n+1):
for j in range(0,i+1):
print(" * ",end="")
print()
|
# Finding the second largest and second smallest number in a list
while True:
n = input("Enter a no. for n length of list : ")
try:
n = int(n)
a = list(map(int, input("Enter a list : ").strip().split()))[:n]
break
except:
print("Wrong Entry: Try Again!! 'Enter a n... |
'''
Polymorphism is when different Classes share the same method name.
For Example: Below we call 'speak()' from two different classes.
'''
class Dog():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says Woof!"
class Cat():
def __init__(self,name) -> None:
s... |
# Demonstrate how to return Index and Value information from lists using the enumerate function
courses = ["math", "english", "history", "politics", "art", "physics", "chemistry"]
def loop_index(target):
for item in enumerate(target):
print(item)
print("\n")
for count, item in enumerate(target):... |
import csv
''' For technical reasons that you should feel free to blame on Microsoft, you should always
work with csv files in binary mode by including a b after the r or w '''
if __name__ == "__main__":
def process(*args):
print(*args)
with open('tab_delimited_stock_prices.txt', 'r', encoding='utf8') a... |
# stdin and stdout
# If you run your Python scripts at the command line, you can pipe data through
# them using sys.stdin and sys.stdout.
# egrep.py
import sys, re
# sys.argv is the list of command-line arguments
# sys.argv[0] is the name of the program itself
# sys.argv[1] will be the regex specified at the c... |
"""Perceptron model."""
import numpy as np
class Perceptron:
def __init__(self, n_class: int, lr: float, epochs: int):
"""Initialize a new classifier.
Parameters:
n_class: the number of classes
lr: the learning rate
epochs: the number of epochs to train for
... |
# coding: utf8
# изучение функции sorted
# примеры из этого файла лучше выполнять по одному, а не запускать весь
# файл целиком
# функция sorted принимает на вход один обязательный аргумент и три
# необязательных
# первый - то, что нужно отсортировать. Это что-то должно быть итерируемым,
# то есть оно должно поддержи... |
a=['1','2','3','4','5','6','7','8','9']
def printboard():
print(a[0]+'|'+a[1]+'|'+a[2])
print("-----")
print(a[3]+'|'+a[4]+'|'+a[5])
print("-----")
print(a[6]+'|'+a[7]+'|'+a[8])
playeroneturn = True
while True:
printboard()
p=input("choose an available space:")
if(p in a):
if (a[int(p)-... |
a=[]
f=open("newlist.txt")
for i in f:
a.append(i[:-1])
l=list(set(a))
m={}
for i in range(len(l)):
m[l[i]]=i
for i in range(len(a)):
print i,m[a[i]]
|
import unittest
from cards import Hand, Card
class TestHand(unittest.TestCase):
def test_simple(self):
hand = Hand([Card(rank='5', suit='spades')])
self.assertEqual(hand.score(), 5)
def test_soft_17(self):
hand = Hand([
Card(rank='A', suit='spades'),
... |
import math
class Pose:
"""
Represent the x, y, theta pose of an object in 2D space
"""
x = 0.0
y = 0.0
theta = 0.0
def __init__(self, x, y, theta):
self.x = x
"""x coordinate"""
self.y = y
"""y coordinate"""
self.theta = theta
"""rotation in ... |
# state is denoted by a dictionary
import copy
class tic_tac_toe:
def initialize(self):
# Ask the player to make a choice of 'x' and 'o'. If 'x', ask the player
# to select the first move.
while True:
turn = input("Which player do you want to choose, 'x' or 'o': ")
tu... |
#!/usr/bin/python3
''' Function that prints squares of # characters
size is the lenght of the square
Doesn't return anything, only prints
'''
def print_square(size):
'''This function raise Type error if the size if not a
integer.
Raise error if size is less than 0.
'''
if type(size) != int:
... |
#!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
if len(tuple_a) >= 2:
ta_1 = tuple_a[0]
ta_2 = tuple_a[1]
elif len(tuple_a) == 1:
ta_1 = tuple_a[0]
ta_2 = 0
else:
ta_1 = ta_2 = 0
if len(tuple_b) >= 2:
tb_1 = tuple_b[0]
tb_2 = tuple_b[1]... |
#!/usr/bin/python3
def uniq_add(my_list=[]):
uniq = set(my_list)
res = 0
for i in uniq:
res = res + i
return (res)
|
#!/usr/bin/python3
''' Function that prints a text again but
adding 2 new lines if find the characters
'.' or '?'
'''
def text_indentation(text):
''' This function raise TypeError if the value givn
is not a string.
And Remove spaces at the beginnig or end of the lie
'''
i = 0
if type(text) !=... |
#!/usr/bin/python3
""" File with the class Rectangle """
from models.base import Base
class Rectangle(Base):
""" __init__ method """
def __init__(self, width, height, x=0, y=0, id=None):
""" init method of rectangle """
self.width = width
self.height = height
self.x = x
... |
#!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
p_number = -((number * -1) % 10) if number < 0 else number % 10
if p_number == 0:
print("Last digit of {:d} is {:d} and is 0".format(number, p_number))
elif p_number < 6:
print("Last digit of {:d} is {:d} and is less than 6 and not 0"
... |
"""Prime factorization
Enter a number > 1 or leave empty for default test.
get_prime_factors function returns a dictionary.
Output is printed in exponential form.
"""
def get_prime_factors(num):
"""Returns prime factors of a number in a dictionary."""
test, primes = 2, {}
while test <= num:
if num... |
""" Josephus Problem -- ONELINER """
# Parameter of the function is the list of the soldiers.
j = lambda s: s[0] if len(s) == 1 else j(s[2:] + s[0:1])
# Testing for various cases
for s in range(2, 21):
print(f"{s} soldiers started. Soldier #{j(list(range(1, s+1)))} survived.")
|
"""Demonstration of Cursor Shapes in Tkinter
Custom Cursors downloaded from:
http://www.cursors-4u.com/cursor/2017/03/14/starfruit.html
http://www.cursors-4u.com/cursor/2014/03/05/minecraft-diamond-sword.html
The .cur files must be in the same directory as where the script is run.
.cur works only on Windows. Other oper... |
# Generate Triplets of Left/Right values (Left = 1, Right = 2)
# Basic idea: the possible combinations are 2 * 2 * 2 = 8
# And each position in the triplet can have only one of two values.
# So the result can be mapped from the binary representation of number 0-7 on 3 digits.
left_right = [format(i, '03b') for i in ran... |
'''
Gradient Descent Module
'''
import vectors as vec
import math
import random
# Step function used by gradient to movie step_size amount in direction from v
def step(v, direction, step_size):
return [v_i + step_size * dir_i for v_i, dir_i in zip(v, direction)]
# Safety function that gives new function that ret... |
'''
Artificial Neural Networks Module
'''
import vectors as vec
import matrix as mat
import statistics as stat
import gradientDescent as gd
import dataprocessing as dp
import random
import math
# Step function
def step(x):
return 1 if x >= 0 else 0
# Sigmoid function
def sigmoid(t):
return 1 / (1 + math.exp(-... |
import re
baggage_regulations_raw = open('puzzle_input.txt', 'r').read().split('\n')
baggage_regulations_test = """light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 s... |
# *! Python Problem 5 | Python Tutorials For Absolute Beginners In Hindi #111
# *! The task you have to perform is “Palindromify the List.” This task consists of a total of 10 points to evaluate your performance.
# *! The task is very similar to the previous one i.e. Tutorial #109 ( Pyhton Problem 4)
# *! Problem St... |
"""
# Programmer : Dhruv Patel
# Problem Name : Search
# Used In : Practice
# Used As : Data Processing
# Thoughts =>
# O(N) This program opens the database and split the .csv file into the two coloumns.
# One is a product name and other one is a com... |
from db import user_info
class User():
user_id = 0
def __init__(self, email, firstname, lastname, password):
self.email = email
self.firstname = firstname
self.lastname = lastname
self.password = password
self.user_id += 1
def record_user(self):
user_info['email'].append(self.email)
user_info['passwor... |
# define the function blocks
def addition4(w = 8, x = 4, y = 2, z = 1):
op = w + x + y + z
print(op)
def subtract4(w = 8, x = 4, y = 2, z = 1):
op = w - x - y - z
print(op)
def multiply4(w = 8, x = 4, y = 2, z = 1):
op = w * x * y * z
print(op)
def divide4(w = 8, x = 4, y = 2, z = 1):
op... |
r=int(input("Enter the radius of the circle:"))
print("Area of the circle is:",(3.14*r*r),"Square units") |
a=int(input("Enter a number:"))
b=int(input("Enter a number:"))
temp=a
a=b
b=temp
print("Values after Swapping",a,b) |
#Simple try except block
try:
#a,b = input('Enter twoo numbers, sperated by comma : ').split(',') #if error occurs here i.e zero division then except block will execute, i.e exception is raised
#c = int(a)/int(b)
#print(c)
pass
except ZeroDivisionError:
print('Division by zero is not poss... |
#!/usr/bin/env python
"""
VIN generator
For usage see --help output.
"""
import argparse
import random
class VinGenerator(object):
""" Generates VINs """
@staticmethod
def run_with_args():
""" Read arguments from command line and run accordingly """
# VIN mode
parser = argparse.ArgumentParser(prog="vgen",... |
#!/usr/bin/env python
""" Printer class """
from __future__ import print_function
import sys
import time
class Printer(object):
""" Printer that allows squelching output. """
def __init__(self, squelch=False, verbose=True, name=None):
""" Ctor """
object.__init__(self)
self.squelch = squelch
self.verbos... |
import math
upper = int(input("Enter Upper Limit: "))
print("Number\tSquare Root")
for i in range(2, upper):
sq = math.sqrt(i)
if sq % 2 == 0 or sq % 2 == 1:
print("{0}\t\t{1}".format(i, sq))
|
class Lagrange:
def __init__(self, points):
self.points = points
def lagrange_k(self, point_k, x):
numerator = 1
for k in range (len(self.points)):
if k != point_k:
numerator *= x - self.points[k][0]
denominator = 1
for k in range (len(... |
# Krishna Vamsee Duggaraju
# 800688160
# Let a4 = 10, a3 = 5, a2 = 8, a1 = 1, a0 = 9
# Let the polinomial is 10x^4+5x^3+8x^2+x+9 at x=5
poly = [10, 5, 8, 1, 9]
x = 5
n = len(poly)
def polynomial(poly, n, x):
evl = poly[0]
for i in range(1,n):
evl = evl*x + poly[i]
return evl
print("value of polynomial is ", polyno... |
# KRISHNA VAMSEE DUGGARAJU
# 800688160
h=int(input("Enter hours:"))
p=int(input("Enter pay:"))
def computepay(h,p):
if h>40 :
grosspay = (40*p)+ (h-40)*p*1.5
elif h<=40 :
grosspay = (h*p)
return grosspay
pay = computepay(h,p)
print("gross pay is:",pay)
|
# imports the modules necessary for the program to function
from tkinter import Tk, Label, Button, Frame, Entry, PhotoImage
from Player import Player, card
import random
"""
Names: Ifaz Alam
Date: March 13, 2020
Description: BlackJack Program using Tkinter
NOTE:
It is recommended to run this program through IDLE as ... |
import socket
#Set the port
serverAddressPort = ("localhost", 13000)
#Create a UDP socket connection
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#Allow the user to input a message for the server
message = input("Message to server:")
mbytes = str.encode(message)
#Send the message to the server
cl... |
'''Haz una contrasea con tres letras
de tu nombre y 3 de tu apellido'''
def contrasena():
import random
name=raw_input("Ur name?")
apellido=raw_input("Ur surname?")
print "Ur password is: "+name[0:3]+apellido[0:3]
contrasena()
|
'''Escriba una funcin llamada multiplicacin
que reciba como argumento cuatro nmeros reales
distintos de cero y que devuelva su producto.'''
def multiplicacion():
first=int(input("First Number:"))
second=int(input("Second Number:"))
third=int(input("Third Number:"))
fourth=int(input("Fourth Number... |
L=int(input())
if L>0:
print("Positive")
elif L==0:
print("Nor Postive And Negative")
else:
print("Negative")
|
# Create your first MLP in Keras
from keras.models import Sequential
from keras.layers import Dense
import numpy
import pandas as pd
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from sklearn.preprocessing import LabelEncoder
# fix random seed for reproducibility
numpy.rand... |
# tensorflow와 tf.keras를 임포트합니다
import copy
import numpy
import tensorflow
from tensorflow import keras
# 헬퍼(helper) 라이브러리를 임포트합니다
import numpy as np
import matplotlib.pyplot as plt
example = [[1, 2, 3, 4, 5, 6], # 1
[7, 8, 9, 10, 11, 12], # 2
[13, 14, 15, 16, 17, 18], # 3
[19, 20,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.