text stringlengths 37 1.41M |
|---|
'''
Generate the train and validation errors needed to plot a
validation curve that we can use to select lambda
'''
import numpy as np
from linearRegCostFunction import linearRegCostFunction
from trainLinearReg import trainLinearReg
def validationCurve(X, y, Xval, yval):
'''
returns the train and validation ... |
'''
lots a learned polynomial regression fit over an existing figure.
Also works with linear regression.
'''
import numpy as np
import matplotlib.pyplot as plt
from polyFeatures import polyFeatures
def plotFit(min_x, max_x, mu, sigma, theta, p):
'''
plots the learned polynomial fit with power p and
featu... |
'''
Compute cost and gradient for logistic regression
'''
import numpy as np
from sigmoid import sigmoid
def costFunction(theta, X, y):
'''
computes the cost of using theta as the parameter for logistic
regression and the gradient of the cost w.r.t. to the parameters.
'''
# Initialize some usefu... |
class Car:
def SetType(self,type):
self._Type=type
def GetType(self):
return self._Type
def SetModel(self,model):
self._Model=model
def GetModel(self):
return self._Model
def SetPrice(self,price):
self._Price = price
def GetPrice(self):
... |
i=1
while(i<6):
print("Number {}".format(i))
i+=1
print("App is done")
|
from team import team_search
#First thing user sees.
#Asks user how they'd like to search
#Currently only option avaliable is: Team Search
def getNHLTeam():
first_query = input("""
Please Enter How You Would Like To Search:
-'T' to search by Team:
-'P' to search by Player: COMING S... |
"""
--- Day 5: How About a Nice Game of Chess? ---
You are faced with a security door designed by Easter Bunny engineers that seem
to have acquired most of their security knowledge by watching hacking movies.
The eight-character password for the door is generated one character at a time
by finding the MD5 hash of som... |
#!/usr/bin/env python3
'''Intro to driving robot movement'''
from ev3dev.ev3 import *
#Initialize drive motors
drive_motor_1 = Motor(OUTPUT_B)
drive_motor_2 = Motor(OUTPUT_C)
#Move forward by a certain amount at a certain speed.
#Run both drive motors at speed 250 in the same direction for 800 degrees.
drive_motor_... |
from check_sudoku import check_sudoku
from simple_sudoku_solver import complete_simple_sudoku
from simple_sudoku_solver import check_incomplete
# functions complete sudoku
# identifies empty positions in the grid
def find_empty(grid):
count_row = 0
for row in grid:
count_column = 0
for num in row:
if num ... |
class mylist():
def __init__(self,l):
self.l = l
def extend(self,index):
diff = index + 1 - len(self.l)
if diff > 0:
self.l.extend([ None for x in range(diff) ] )
def __getitem__(self,index):
# self.extend(index) ## depending on your taste
return self.l[in... |
from probability import with_probability
import random
def create_code_mutations(number_of_mutations):
code_mutations = []
for _ in range(number_of_mutations):
code_mutations.append(create_code());
return code_mutations
def create_code():
code = []
available_commands = ["if self.smells_foo... |
#!/usr/bin/env python
"""A more advanced Mapper, using Python iterators and generators."""
from __future__ import print_function
import sys
import re
for line in sys.stdin:
content = re.sub('^\W+|W+$', '',line)
words = re.split("\W+",content)
for idx in range(len(words)-1):
print(words[idx],words[idx+1],'1')
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
... |
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) == 0:
return ''
return s[::-1]
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) == 0:
... |
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if nums == None:
return nums
n = len(nums)
m = len(nums[0])
if n*m == r*c:
... |
'''
read the input data, parse to int list;
create mappings of user -> reviews, item -> reviews
The companion iterator reads thru the input file sequentially, yielding the data of the form: user word id list, item word id list, rating (float)
@author: roseck
@date Feb 28, 2017
'''
#from __builtin__ import dict
impor... |
class client:
def __init__(self, clientId, name):
self.__clientId = clientId
self.__name = name
'''Setters'''
def setId(self, clientId):
self.__clientId = clientId
def setName(self, name):
self.__name = name
'''Getters'''
def getId(self):
return self.__... |
def sortFunction(a, b, index = 0):
if (index == 0):
return a < b
return a[index] < b[index]
def selectionSort(list, function, index = 0):
for x in range(0, len(list) - 1):
xMin = x
for y in range(x + 1, len(list)):
if function(list[y], list[xMin], index):
... |
from exceptions import raiseException
def printInfo():
print("Choose size:")
print("1. 6x5")
print("2. 6x6")
print("3. 7x6")
print("4. 8x7")
print("5. 8x8")
def getXY(x):
if (x == 1):
return (6, 5)
if (x == 2):
return (6, 6)
if (x == 3):
return (7, 6)
if... |
#!/usr/bin/python
# coding: UTF-8
# Author: David
# Email: youchen.du@gmail.com
# Created: 2016-09-17 11:09
# Last modified: 2016-09-17 11:09
# Filename: solution.py
# Description:
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
f = ... |
#!/usr/local/bin/python3
# coding: UTF-8
# Author: David
# Email: youchen.du@gmail.com
# Created: 2017-02-13 09:54
# Last modified: 2017-02-13 10:25
# Filename: solution2.py
# Description:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.l... |
#!/usr/local/bin/python3
# coding: UTF-8
# Author: David
# Email: youchen.du@gmail.com
# Created: 2017-02-11 13:45
# Last modified: 2017-02-11 13:45
# Filename: solution.py
# Description:
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
... |
from math import sqrt
#for...else
broke_out=False
for n in range(99,81,-1):
root=sqrt(n)
if root==int(root):
print n
broke_out=True
break
if not broke_out:
print 'Didn\'t find it!'
|
import sys,shelve
def store_person(db):
"""
Query user for data and store it in the shelf object
"""
pid=raw_input("Enter unique ID number:")
person={}
person['name']=raw_input('Enter name:')
person['age']=raw_input('Enter age:')
person['phone']=raw_input('Enter phone number:')
db[pid]=person
def lookup_pe... |
from pessoa import Person
import time
class Employee(Person):
def __init__(self,name, phone, email, salary, da):
self.salary = salary
self.da = da
super().__init__(name, phone, email)
def work_days(self, da, name):
import datetime
datapadrao = datetime.date(... |
import pandas as pd
def get_top_cities_with_max_hotels(df: pd.DataFrame) -> pd.DataFrame:
"""
According data grouped by country, city finds one city in every country with the biggest amount of hotels in it.
Return dataframe with full info about top cities, hotel parameters.
:param df: Pandas dataframe... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 4 19:55:50 2021
@author: MorenoW
"""
def isYearLeap(year):
if year%4 == 0 and year%100 != 0 or year%400 == 0:
return True
else:
return False
testData = [1900, 2000, 2016, 1987]
testResults = [False, True, True, False]
for i in range(len(testDa... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 5 19:53:01 2021
@author: MorenoW
"""
def fibonacci(number):
a = 0
b = 1
while a < number:
print(a, end=" ")
c = a + b
a = b
b = c
#a, b = b, a+b
#print()
n = int(input("Ingrese un número para calcular: "))... |
#!/usr/bin/python
from bs4 import BeautifulSoup
import re
import csv
import os.path
def findColor(score):
""" returns the color used to represent the numerical score """
if score >= 0 and score < 5:
color = '#F5F9FC'
elif score >= 5 and score < 10:
color = '#EBF4FA'
elif score >= 10 a... |
# using library sys function argv
from sys import argv
# argv use 2 argument script and filename
script, filename = argv
# open file .txt
txt = open(filename)
# print filename and use .read() to show content of the file
print "Here's your file %r" % filename
print txt.read()
# using raw_input to load filename
print "I'... |
class StringUtils:
"""
Contains common operations related to string processing.
"""
@staticmethod
def find_all(string, substring):
start = 0
while True:
start = string.find(substring, start)
if start == -1:
return
yield start
... |
from P_match import p_match as pm
from Queue import Queue
from LinkedList import LinkedList
# exp = "[5-(4*6)+{3(6-4)[3]}]"
# if pm(exp):
# print("Valid")
# else:
# print("Invalid")
# q = Queue("1")
# q.insert_at_rear("2")
# q.insert_at_rear("3")
# q.insert_at_rear("4")
# q.insert_at_rear("2")
# q.insert_at_r... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 26 11:52:14 2017
@author: GISLAB-2
"""
import numpy as np
def dms2dd(AngleObj):
"""degree minutes to decimal degree
input:
AngleObj : Object with deg,mi,sec record
output:
dd : decimal degree (float)"""
return AngleObj.deg+(AngleObj.mi/60)... |
prod = str(input("Qual o código do produto? "))
if prod == '1':
print("Pizza!")
elif prod == '2':
print("Hamburger!")
elif prod == '3':
print("Refrigerante!")
elif prod == '4':
print("Batata frita!")
else:
print("Produto não encontrado")
|
idade = str(input("Qual a idade do atleta? "))
if idade >= '05' and idade <= '10':
classi = 'Infantil'
elif idade >= '11' and idade <= '15':
classi = 'Juvenil'
elif idade >= '16' and idade <= '20':
classi = 'Junior'
elif idade >= '21'and idade <= '25':
classi = 'Profissional'
else:
print("Idade não aceita!")... |
def make_alph():
alph = ""
for i in range(ord('a'), ord('z') + 1):
alph += chr(i)
for i in range(ord('!'), ord('A') - 1):
alph += chr(i)
for i in range(ord('а'), ord('я') + 1):
alph += chr(i)
alph += 'ё'
alph += ' '
alph += "\""
return alph
def read_keys_from_fi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Yu Zhou
# ****************
# Descrption:
# Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
#
# push(x) -- Push element x onto stack.
# pop() -- Removes the element on top of the stack.
# top() -- Get the top element.... |
import random
answer = random.randint(1,10)
print("guess the number b/w 1 to 10")
guess=0
while (guess!=answer):
guess=int(input())
if(guess ==0):
break
elif(guess > answer):
print("please guess something lower" )
elif(guess < answer):
print("Please guess something hig... |
def longest_palindrome(s):
res = ""
for i in range(len(s)):
res = max(helper(s, i, i), helper(s, i, i+1), res, key=len)
return res
def helper( s, l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return s[l+1:r]
test1 = "babad"
print(longest_pal... |
def reverse_words(string):
return " ".join(string.split(" ")[::-1])
test1 = "Hello World And Stacey"
test2 = ""
test3 = "l mao"
print(test1)
print(reverse_words(test1))
print(test2)
print(reverse_words(test2))
print(test3)
print(reverse_words(test3)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 22 14:57:36 2017
@author: caper911
"""
def quicksort(v, left, right):
if left >= right:
return v
key = v[left] ##基准数key
low = left
high = right
while low < high:
while (low < high) and ... |
'''
python3
Author: Anthony Silva
Objective: Given two sequences 𝐴 = (𝑎1,𝑎2,...,𝑎𝑛) and 𝐵 = (𝑏1,𝑏2,...,𝑏𝑚),
find the length of their longest common subsequence, i.e., the largest
non-negative integer 𝑝 such that there exist indices 1 ≤ 𝑖1 < 𝑖2 <···< 𝑖𝑝 ≤ 𝑛
and 1 ≤ 𝑗... |
'''
python3
Author: Anthony Silva
Description: A thief finds much more loot than his bag can fit. Help him
to find the most valuable combination of items assuming that any
fraction of a loot item can be put into his bag. (Implement a greedy
algorithm for the fractional knapsack problem)
Input: The first line... |
class Node():
def __init__(self, value):
self.value = value
self.next = None
class Sll():
def __init__(self):
self.head = None
self.tail = None
self.len = 0
def insert(self, value, index):
if(index > self.len or index < 0):
print('Not possib... |
import queue
class Node():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree():
def __init__(self):
self.root = None
def insert(self, value):
newNode = Node(value)
if (not self.root):
print('Insert... |
class Stack:
def __init__(self, size):
self.size = size
self.st = [None] * size
self.topOfStack = 0
def push(self, value):
if(self.topOfStack == self.size):
print('Size overflow, cant insert')
return
self.st[self.topOfStack] = value
se... |
import json
import urllib2
from urllib import urlopen
# with open("new1.txt", "r") as myfile:
# # blank
# print "test"
test = json.load(urllib2.urlopen("http://api.football-data.org/alpha/soccerseasons/354/teams"))
for team in test['teams']:
print team['_links']['players']['href'], team['code'], team['name']
... |
# give an array sort it
import math
layer_left = 0
layer_right = 0
# Merges two subarrays of arr[].
# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(array,left,mid,right):
# the elements in the left
n1 = mid - left + 1
# the elements in the right
n2 = right - mid + 1
# init... |
def solution(numbers):
numbers = list(map(str, numbers))
numbers.sort(key=lambda x: x*3, reverse=True)
return str(int(''.join(numbers)))
#string 대소비교
#첫 문자부터 비교하여 동일한 인덱스에 더 작은 문자열이 나오면 작은 것임.
#'121121121', '121212'의 경우 4번째 인덱스에서 '121212'가 더 크다고 인식함.
|
class ListNode:
def __init__(self, value=None):
self.value = value
self.next = None
node0 = ListNode(3)
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node4.next = node5
node3.next = node4
node2.next = node3
node1.next = node2
node0.next =... |
#Adds to the sample group
#Author: Henry Woo <hcwoo2>
from PIL import Image
import numpy as np
import csv
filename = raw_input("Enter filename with extension.\n")
temp = Image.open(filename)
maxsize = (640, 640)
temp = temp.resize(maxsize, Image.ANTIALIAS)#shrink image
temp = np.asarray(temp)#array to ex... |
from math import floor, ceil, log2
import numpy as np
def bit(number, index):
"""Return the indexth bit of number."""
return (number >> index) & 1
def sum_bits(number):
"""Return the sum of digits in the binary representation of number."""
if number == 0:
return 0
sum_ = 0
for i in r... |
from math import sqrt
def isPrime(number):
if number == 0:return 0
if number == 1:return 0
if number == 2:return 1
if number % 2 == 0:return 0
end = int(sqrt(number)) + 1
for i in range(3,end,2):
if number % i == 0:return 0
return 1 |
from math import sqrt
def isPrime(number = 1):
if number <= 1:return False
if number == 2:return True
if number % 2 == 0:return False
end = int(sqrt(number)) + 1
for i in range(3, end, 2):
if number % i == 0:return False
return True
def getPrimeList(end = 100):
primeList = [number for number in range(2, en... |
#-*- coding:utf-8 -*-
#answer is 142857 (0.06秒) 2015/2/3
from time import time
def toList(number):
dividedDigitList = []
while number != 0:
dividedDigitList.insert(0, number % 10)
number //= 10
return dividedDigitList
def sameNumberInList(a,b):
if len(a) != len(b):
return 0
for index in range(len(a)):
... |
#
n = int(input(" : "))
X = []
Y = []
k = 1
for i in range(n):
x = int(input("x: "))
X.append (x)
y = int(input("y: "))
Y.append (y)
while k < n:
for i in range(n-k):
if X[i] > X[i+1]:
X[i],X[i+1] = X[i+1],X[i]
Y[i],Y[i+1] = Y[i+1],Y[i]
k += 1
a = i... |
# Continue & Pass
# Continue
# Una vez activado, salta la vuelta actual en el For, pasando a la siguiente.
"""
for letra in "Python":
if letra == "h":
continue
print(f"Viendo la letra: {letra}")
"""
"""
nombre = "Aprendiendo Python"
contador = 0
for i in nombre:
if i == " ... |
# Tuplas (Listas inmodificables, que solo se pueden leer, van con () ). Son mas rapidas y pesan menos
# Las Tuplas pueden pasar a ser listas y viceversa, con copías de estas
tupla = ("Messi", "Maradona", "Pele" )
lista = list(tupla)
tupla = tuple(lista)
print(tupla)
|
# Bucle While infinito y Bucle While definido
import math
numero = int(input("Digite un numero: "))
while numero < 0: # Mientras la condicion se cumpla, se seguira ejecutando lo que este dentro de la funcion
print("Error, no ingreso un numero positivo")
numero = int(input("Digite un numero: "))
... |
# Constructores, Encapsulamiento e Instancias
class Coche():
# Es indispensable usar el self. dentro de un constructor/comportamiento
def __init__(self): # Constructor
self.largoChasis = 250 # Propiedad
self.anchoChasis = 100 # Propiedad
self.__ruedas = 4 # Propiedad... |
year="1900"
babynames=[]
name_count={}
while year<=2017:
filename= "data/names_"+year+".txt"
file= open(filename,"r")
reading= filename.readline().split('|')
names= reading[1:2]
for i in names:
if i not in babynames:
babynames.append(i)
name_count[i]=1
... |
#!/usr/bin/env python3
# inscribed_polygons.py
''' NOTE: After less than 10min of runtime, the script finds successfully the first 15 decimals, but seems to stop there, probably because
of the limitations that are involved due to the use of the math.radian function required to use math.sin (math.sin only works with ra... |
from random import randint
n, m, s = randint(1, 3), 2, randint(5, 10)
print(n, m, s)
L = 1
def Print():
global L
L += randint(1, 3)
print(L, end = ' ')
for i in range(0, n):
Print()
Print()
print()
|
#!/usr/bin/python3
from random import *
n=3000;
print(n)
for i in range(1, n+1):
for j in range(1, n+1):
x=randint(0,1000)
if i == j:
print(0,end="")
else:
if (x == 0) :
print(0,end="")
else :
print(1,end="")
print();
|
print('Give me a negative, floating-point number.\nI\'ll turn it into a positive integer!')
negFloat = float(input())
print(round(abs(negFloat)))
|
inventory = {'torch': 6, 'rope': 3, 'gold': 88}
loot = ['gold', 'dagger', 'gold', 'gold', 'rope']
def displayInventory(inv):
print('Inventory:')
total = 0
for k, v in inv.items():
print(v, k)
total += v
print('Total number of items:', total)
def addToInventory(inv, loot):
for i in range(len(loot)):
... |
# -*- encoding: utf-8 -*-
# grep2.py - Segunda versão do nosso utilitário de busca
# Importar os Módulos os e sys para obter informação sobre o ambiente em que o programa está rodando.
import os
import sys
# criamos dois tipos de exceção que usaremos no nosso código.
class ParametroInvalido(Exception):
pass
clas... |
#!/usr/bin/env python3
#- * -coding: utf - 8 - * -
"""
Created on Thu May 2 14: 49: 22 2019
@author: anmol
"""
import random
import datetime as dt
'''
Get a random point between two coordinates
'''
def get_point_by_position(position):
if (position == "enter"):
return -5, 301
elif (position == "registration")... |
import math
from fractions import gcd
class Point:
def __init__(self, curve, x, y, inf = False, force = False):
self.marge = curve.marge # marge determined once in curve
self.x = x
self.y = y
self.curve = curve
self.inf = inf ... |
import matplotlib.pyplot as plt
import numpy as np
import math
#finds the line of best fit with least squrae method
def bestFit(x, y):
#this is the numerator for the slope
def crossSum(x,y):
n = float(len(x))
crossSum = 0
for i in range(len(x)):
crossSum += (x[i] - np.sum(x... |
a_list = [3,4,-2,-30,14,9.3,3.4]
a_list.sort()
print(a_list)
b_list = ['python','swift','ruby','go','kotline','erlang']
b_list.sort()
print(b_list)
b_list.sort(key=len)
print(b_list)
b_list.sort(key=len,reverse=True)
print(b_list) |
# 定义全局空间的foo函数
def foo():
print("全局空间的foo方法")
# 定义全局空间的bar变量
bar = 20
class Bird:
# 宝义Bird空间的foo函数
def foo():
print("Bird空间的foo方法")
# 定义Bird空间的bar变量
bar = 200
# 调用全局空间的函数和变量
foo()
print(bar)
# 调用Bird空间的函数和变量
Bird.foo()
print(Bird.bar) |
class Person:
'这是学习python类定义的第一个Person类'
# 下面定义一下类变量
hair = 'black'
def __init__(self,name='gavin',age=20):
# 下面为Person对象增加两个实例变量
self.name = name
self.age = age
# 下面定义一个say方法
def say(self,content):
print(content)
# 调用Person类的构造方法,返回一个Person对象
# 将Person对象赋值给P变量
... |
x = map(lambda x:x*x,range(8))
print([e for e in x])
y = map(lambda x:x*x if x%2 == 0 else 0,range(8))
print([e for e in y]) |
class People:
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print("%s eat....." % self.name)
def sleep(self):
print("%s sleep ...." % self.name)
def talk(self):
print("%s talk ....." % self.name)
class Man(People):
def __init__... |
# Wikipedia記事のJSONファイルを読み込み,「イギリス」に関する記事本文を表示せよ.
# 問題21-29では,ここで抽出した記事本文に対して実行せよ.
import gzip
import json
def load_article(fname, title):
with gzip.open(fname, 'rt') as data_file:
for line in data_file:
data_json = json.loads(line)
if data_json['title'] == title:
re... |
# 与えられたシーケンス(文字列やリストなど)から
# n-gramを作る関数を作成せよ.
# この関数を用い,"I am an NLPer"という文から単語bi-gram,
# 文字bi-gramを得よ.
def str2wl(src):
return [s.split()
for s in src.rstrip('.').split('.')
]
def str2cl(src):
return [list(w)
for w in
[''.join([c
for c in w
... |
class Avion:
def __init__(self, companie,ruta_de_zbor, ora_de_zbor):
self.companie = companie
self.ruta_de_zbor = ruta_de_zbor
self.ora_de_zbor = ora_de_zbor
def decoleazaAvionul(self):
print("Avionul decoleaza")
def aterizeazaAvionul(self):
print("S... |
# Insert 5 cars into the inventory table
# 3 Fords, and 2 Hondas
import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
# create a tuple of information, then executemany
cars = [
("Ford", "Mustang", 5),
("Honda", "Civic", 12),
("Honda", "CRX", 3),
... |
# encapsulation-1
# Encapsulation means to preserve data in classes using methods
class MyClass(object):
def set_val(self, val):
self.value = val
def get_val(self):
print(self.value)
return self.value
a = MyClass()
b = MyClass()
a.set_val(10)
b.set_val(100)
a.... |
# encapsulation
# Encapsulation means to preserve data in classes using methods
# In this example, we have two methods, `set_val` and `get_val`.
# The first one sets the `val` value while the second one
# prints/returns the value.
class MyClass(object):
def set_val(self, val):
self.value = va... |
#Autor: Cecilia Daniela Olivares Hernández, a01745727
#Descripción: Calcula el precio total a pagar de los boletos comprados para un concierto.
#Esta funcion calcula el rendimiento del automovil en km/litros
def calcularRendimientoKm(km, litros):
rendimientoKm = km / litros
return rendimientoKm
#Esta ... |
import csv
import numpy as np
import random as rand
import headerNode as head
class fileParse:
def __init__( self, filePath ):
"""fileParse takes in the file path for a csv file and prepares it for analysis"""
self.headers = []
self.data = []
self.dataShape = 0
self.filepa... |
import random
# Read in all the words in one go
with open("input.txt") as f:
words = f.read()
# TODO: analyze which words can follow other words
# Your code here
def print_random_sentence(input_string):
lookup = {}
individual_words = input_string.split()
for idx in range(len(individual_words)):
... |
#!/usr/bin/env python3
# author: https://github.com/m0nkeyplay
# August 25, 2020 - original script written
# Simply scramble and descramble cac messages.
# Take input from a user.
# Returns message to screen.
# Start a conversation about programming and ciphers
import os
import cac
startMessage = """
╔... |
"""
This module is for functions that related to file opening and creating.
"""
from datetime import datetime
import stars_filtering
def data_file_has_an_comments(tsv_file) -> bool:
"""
Checking if tsv or csv file has a comments
"""
for row in tsv_file:
if row[0] == '#':
tsv_file... |
import abc
class ResponseStrategy(abc.ABC):
@abc.abstractmethod
def response(self):
pass
class NegativeResponse(ResponseStrategy):
def response(self, event):
reaction = {'health':'Yay ', 'death':'Yay ', 'win': 'Boo '}
print(reaction[event], end=" ")
class PostiveResponse(Respon... |
# Your goal is to create a function that removes the first and last letters of a string. Strings with two characters or less are considered invalid. You can choose to have your function return null or simply ignore.
# Get string passed as command line argument.
import sys
string = sys.argv[1]
print("Original string:... |
# https://dev.to/thepracticaldev/daily-challenge-7-factorial-decomposition-176o
import sys
import math
def getnextprime(prime):
notprime = True
while (notprime):
prime += 1
for x in range(2, prime):
if prime % x != 0:
notprime = False
return prime
def decompose... |
from random import randrange
from util import tah
def tah_pocitace(pole, symbol_pocitace):
# hraje xxx
#def tah_xxx(pole):
if "-xx" in pole:
cislo_policka = pole.index("-xx")
print("Počítač hraje na políčko číslo:", cislo_policka)
return pole[:cislo_policka] + "x" + pole[cislo_policka... |
# Mike Hickey
# Wentworth Institute of Technology.
# Black Jack Game For AI
# This script will allow the user to play Black Jack.
# Imports
import numpy as np
import random# The RNG used to pick cards.
from datetime import datetime # Used to seed the RNG
import os
os.chdir("dataset")
# A card has a value and a nam... |
import pandas as pd
def timestamp_to_month_weather(timestamp):
"""Takes a timestamp as input and returns the month. Jan is 1, Feb is 2, etc."""
timestamp = pd.to_datetime(timestamp)
return timestamp.month
def timestamp_to_day_weather(timestamp):
"""Takes a timestamp as input and returns the day of the... |
import random
import utilities
# creature class, has name string and size variable
class Mob:
def __init__(self, name, size):
self.name = name
self.size = size
# lists of encounters
# WARNING! Search algorithm means set must contain ONLY other sets OR objects.
beastCommon = [Mob('goblins', 'some'... |
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, roomIn, items=None):
self.name = name
self.roomIn = roomIn
self.items = items
def move(self, direction, roomIn):
attribute = direction
# Trick learned fro... |
# by y_dd
# 时间 2021/04/11
r=range(10)
print(r)
print(list(r))
r=range(1, 9)
print(list(r))
r = range(1,9,2)
print(list(r), type(r))
print(3 in r)
print(4 not in r)
for i in range(0, 9):
print(i)
for _ in range(0, 3):
print("我在这里")
#for else
for item in range(0, 2):
a=input("请输入")
... |
#! /usr/bin/env python
# ----------
# User Instructions:
#
# Define a function, search() that takes no input
# and returns a list
# in the form of [optimal path length, x, y]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to the goal, your fu... |
#! /usr/bin/env python
# ----------
# User Instructions:
#
# Create a function optimum_policy() that returns
# a grid which shows the optimum policy for robot
# motion. This means there should be an optimum
# direction associated with each navigable cell.
#
# un-navigable cells must contain an empty string
# WITH a sp... |
# Jan Lukas Strozyk
# 05-28-2018
# HOMEWORK 3
# PART ONE: Lists
numbers = [4, 5, 1, 10, 200, 34, 22, 19, 43, 56, 32, 11, 40, 82, 23, 43, 12, 65, 10]
# 1) Count how many numbers are in the list. Use a for loop, do NOT use len.
n = 0
for num in numbers:
n = n+1
print("There are", n, "numbers in the list.")
# 2) Use a... |
# Python Crash Course by Eric Matthes
# Chapter 09: Classes
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
# Exercise 9-1
# class Restaurant:
# """
# A simple attempt to model a restaurant.
# """
# def __init__(self, name, cuisine):
# """
# Initialize ... |
# Python Crash Course by Eric Matthes
# Chapter 04: Working with lists
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
# Exercise 4-1
# pizza_flavors = ['margherita', 'mozzarella', 'pepperoni']
# for flavor in pizza_flavors:
# print(f"I like {flavor} pizza.")
# print("I really lo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.