text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# parsing a date (what day were you born on?)
from datetime import datetime
line = input("Enter your date of birth (DD/MM/YYYY): ")
birthday = datetime.strptime(line, "%d/%m/%Y")
print("You were born on a {0:%A}".format(birthday)) |
# Quick Sort is another sorting algorithm which follows divide and conquer approach.
# It requires to chose a pivot, then place all elements smaller than the pivot on the left of the pivot and all elements larger on the right
# Then the array is partitioned in the pivot position and the left and right arrays followth... |
"""
Data and data formatting
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('data.csv')
print(data[:10])
# Function to help us plot
def plot_points(data):
X = np.array(data[['gre', 'gpa', 'rank']])
y = np.array(data['admit'])
admitted = X[np.argwhere(y == 1... |
import re
for line in range(int(input())):
string = ''
string = re.sub(r'(?<= )&&(?= )','and',input())
string = re.sub(r'(?<= )\|\|(?= )','or',string)
print (string)
|
class Bike(object):
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print self.price
print self.max_speed
print self.miles
return self
def ride(self):
self.miles += 10
... |
def coinTosses():
countH = 0
countT = 0
for i in range (1,5001,1):
import random
hot = random.randrange(1,101)
if hot % 2 == 0:
countH += 1
print ("Attempt # " + str(i) + " Throwing a coin... It's a head! ... Got " + str(countH) + " head(s) so far and " + st... |
#!/usr/bin/env python3
import sys
vowelCount = {
"e": 0,
"a": 0,
"i": 0,
"o": 0,
"u": 0,
}
text = sys.stdin.read()
i = 0
while i < len(text):
if text[i].lower() in vowelCount:
vowelCount[text[i].lower()] += 1
i += 1
tups = []
for a, b in vowelCount.items():
tup = a, b
tups.... |
#!/usr/bin/env python3
from re import findall
date = r'\b\d+[/-]\d+[/-]\d+\b'
phone = r'\b\d{2}[-\s]\d{7}\b'
email = r'\b(?:\w+\.)*\w+\@\w+\.\w+(?:\.\w+)*\b'
ldate = r'\b\d{2}[\s/-]\w{3}[\s/-]\d{2}\b'
if __name__ == "__main__":
with open("test.txt") as f:
s = f.read()
print(findall(date, s))
prin... |
#!/usr/bin/env python3
def minimum(l):
if len(l) == 0:
raise ValueError('Cannot find the minimum of an empty list.')
elif len(l) == 1:
return l[0]
else:
minNumber = minimum(l[1:])
mymin = l[0]
if minNumber < mymin:
mymin = minNumber
return mymin
|
def collatz_seq(n):
global step
step+=1
if n==1 or n==2:
return str(1)
elif n%2:
return str(3*n+1)+','+collatz_seq(3*n+1)
else:
return str(n//2)+','+collatz_seq(n/2)
n=raw_input('Enter number: ')
step=0
print collatz_seq(int(n))
print 'Number of step: ',step |
import sys
def table(n):
for i in range(1,13):
print('{0:2} X {1:2} = {2:^}'.format(n,i,i*int(n)))
def main():
for x in range(1,len(sys.argv)):
print('Table of {}'.format(sys.argv[x]))
print('{}'.format('-'*12))
table(sys.argv[x])
print('{}'.format('='*12))
if __name__=='__main__... |
import random
from random import randint
def generate_file(N=50, M=30, file_name='data/list_to_open.txt'):
random.seed(2390)
file = open(file_name, 'w')
n = N * randint(1, 20)
file.write("N = " + str(N) + "\n")
file.write("M = " + str(M) + "\n")
for i in range(n):
file.write(str(randi... |
import gym
import pygame
import numpy as np
from math import sqrt
ENV_WIDTH = 750
ENV_HEIGHT = 750
class Agent:
def __init__(self, name, board):
"""
This is the agent of the digitized environment. The agent is supposed to try riding around the environment and minimize the amount of collisions whil... |
def twostring(a,b):
firstlet=a[0]+b[0]
middlelet=a[int(len(a) / 2):int(len(a) / 2) + 1] + b[int(len(b) / 2):int(len(b) / 2) + 1]
lastlet=a[-1]+b[-1]
final=firstlet+middlelet+lastlet
print(final)
twostring("america","japan")
|
def greatestnum(a,b,c):
if a>b and a>c:
greatest=a
elif a<b and b>c:
greatest=b
else:
greatest=c
print(f"greatest number of {a},{b} and {c} is {greatest}")
greatestnum(1000,9888,870)
|
l1=["harry","soham","sachin","rahul"]
# i=0
# while i<len(l1):
# print("Happy birthday")
# i=i+1
for name in l1:
if name[0]=="s" or name[0]=="S":
print("Happy birthday")
else :print(l1)
|
dict1={
"Hello":"harsh",
"fruit":"mango",
23:"harsh",
"list":[12,45,67,54],
"tuple":(45,67,34,56),
"dictionary":{
"hello":1,
"hi":2,
}
}
print(dict1)
print(dict1["fruit"])
print(type(dict1))
print(dict1["dictionary"]["hello"]) |
set3={2,4,5,(2,3,4),'hi',True}
print(set)
print(type(set))
set1={}
print(set1)
print(type(set1))
set2=set()
print(set2)
print(type(set2)) |
def diagonaldiff(a,b):
d1=0
d2=0
for i in range(0,b) :
for j in range(0,b):
if i == j :
d1 +=a[i][j]
if i==b-j-1:
d2+=a[i][j]
print(d1-d2)
a=3
b=[[11, 2, 4],
[4 , 5, 6],
[10, 8, -12]]
diagonaldiff(a,b)
|
Dict1={
"Key 1":"value 1",
"key 2":"value 2",
2:[3,4,6,8],
"tuple":(23,56,46,88),
}
print(list(Dict1.keys()))
print(list(Dict1.values()))
print(list(Dict1.items()))
Dict1.__setitem__("key3","value4")
print(Dict1)
# Dict2={
# "Key 1":"value1",
# "key5":"value7",
# "kay6":"va... |
a="once upon a time there was a man who used do farming in his land"
print(len(a))
print(a.capitalize())
print(a.find("time"))
print(a.startswith("once"))
print(a.endswith("land"))
print(a.replace("man","woman"))
print(a.count("once")) |
import math
# This method is Iterative way to find a element is Sorted array
# Algo : Binary Search
# prerequisite Array must be sorted.
def bin_search(arr,l,r,x):
while(l <= r):
mid = int(math.floor(l + (r - l)/2));
if (arr[mid] == x):
return mid
elif (arr[mid] > x):
r = mid-1
... |
import random
import time
combinations = [
[1,2,3],[4,5,6],[7,8,9],
[1,4,7],[2,5,8],[3,6,9],
[1,5,9],[3,5,7]
]
positions = [i for i in range(1,10)]
positions_occupied =[]
def gameBoard():
print(
f"""
{positions[0]} | {positions[1]} | {positions[2]}
-------... |
from collections import defaultdict
salaries_and_tenures = [
(83000, 8.7), (88000, 8.1), (48000, 0.7), (76000, 6), (69000, 6.5),
(76000, 7.5), (60000, 2.5), (83000, 10), (48000, 1.9), (63000, 4.2),
]
salary_by_tenure = defaultdict(list)
for salary, tenure in salaries_and_tenures:
salary_by_tenure[tenure]... |
"""ユークリッドの互除法"""
def swap(a, b):
return b, a
def gcd(a, b):
X = max(a, b)
Y = min(a, b)
step = 0
while(Y != 0):
X %= Y
X, Y = swap(X, Y)
step += 1
return X, step
def main():
while(True):
X, Y = map(int, input().split())
if X == 0 and Y == 0:
... |
import numpy as np
#Generally we want to iterate through our data in a random order
def in_random_order(theta):
"""Generates elements of data in random order"""
indexes = [i for i,_ in enumerate(data)] # creates a list of indices
random.shuffle(indexes) # shuffles them
for... |
# Basic decision tree function
import math
import random
from collections import defaultdict
from functools import partial
# Entropy is a notion of "how much information"
# It is used to represent the uncertainty of data
def entropy(class_probabilities):
"""given a list of class probabilities, compute the... |
#creating a dictionary
d = {'day1':'Sunday', 'day2':'Monday', 'day3':'Tuesday','day4':'Wednesday', 'day5':'Thursday','day6':'Friday'}
print("Printing the dictionary:",end = "\n")
print(d,end = "\n")
#Adding an element to the dictionary
d['day7'] = 'Saturday'
print("After adding an element to dictioanry:",end ... |
# コメント。 #から初めて1行が認識される。
# 変数宣言。型はない。初期化するなら任意の値も
a = 'Hello world'
print(a) # Hello world
a = 1
print(a) # 1
# 関数宣言。 def 関数名 (引数) :で定義。
def addNumber(num1, num2) :
return num1 + num2
# 呼び出しは名称と引数を合わせるだけ
print(addNumber(1 ,2)) # 3
# class宣言もできる。
"""
DocString。ダブルクォートで囲った範囲に適応される。
このクラスは共通処理を提供しています。
"""
class B... |
"""
Vytvoř program na prodej vstupenek do letního kina. Ceny vstupenek jsou v tabulce níže.
Datum Cena
1. 7. 2021 - 10. 8. 2021 250 Kč
11. 8. 2021 - 31. 8. 2021 180 Kč
Mimo tato data je středisko zavřené.
Tvůj program se nejprve zeptá uživatele na datum a počet osob, pro které uživatel chce vs... |
def is_valid_file_name():
'''()->str or None'''
file_name = None
try:
file_name = input("Enter the name of the file: ").strip()
f = open(file_name)
f.close()
except FileNotFoundError:
print("There is no file with that name. Try again.")
file_name = None
return... |
from expel_1 import FilePathTokenizer
import argparse
tokens = FilePathTokenizer()
parser = argparse.ArgumentParser(description='File Path Tokenizer')
parser.add_argument("-f", "--filepaths", nargs='+', type=str, help="Expects any number of file paths, example command line: $ python example.py -f 'filepath1 filepa... |
def raizes (a,b,c):
delta = (b*b)-(4*a*c)
if delta >= 0:
raiz1 = (-b+(delta**0.5))/(2*a)
raiz2 = (-b-(delta**0.5))/(2*a)
print ('Raíz 1: ', raiz1)
print ('Raíz 2: ', raiz2)
retorno = 0
else:
re_raiz = (-b)/(2*a)
im_raiz=((-delta)**0.5)/(2*a)
pr... |
"""
This is an example of using Bayesian A/B testing
"""
import pymc as pm
# these two quantities are unknown to us.
true_p_A = 0.05
true_p_B = 0.04
# notice the unequal sample sizes -- no problem in Bayesian analysis.
N_A = 1500
N_B = 1000
# generate data
observations_A = pm.rbernoulli(true_p_A, N... |
from abc import ABC, abstractmethod
class Engine:
pass
class ObservableEngine(Engine):
""" Heir of Engine class"""
def __init__(self):
self.__subscribers = set()
def subscribe(self, subscriber):
self.__subscribers.add(subscriber)
def unsubscribe(self,subscriber):
self._... |
#tuple is immutable data structue. They are enclosed in parantheses
t1 = ('apple', 100, 120.35, 'hello')
t2 = (1458, 'as', 'tuple')
l1 = [100, 200, 300]
t3 = () # empty tuple
t4 = (50,) # even if have only one object in tuple we need to use comma
# accessing tuple
print t1[0]
print t1[:2]
print t1[2:]
#tuple is imm... |
hrs = input("Enter Hours:")
hrs = float(hrs)
rph = input("Rates per hour: ")
rph = float(rph)
if (hrs <= 40):
pay = hrs*rph
print(pay)
else:
extrahour = (hrs - 40)
pay = (40 * rph) + (extrahour * 1.5 * rph)
print(pay)
|
from sys import argv
script, filename = argv
# opens the file that you enter
txt = open(filename)
# replace filename with the name you enter and print
print(f"Here's your file {filename}: ")
# reads the opened file and then prints the content
print(txt.read())
# asks you to enter the filename again
print("Type the fil... |
class Solution(object):
""" Encapsulates cryptic crossword solutions
Attributes:
score: an indication of how likely the solution is to be correct
notes: newline separated notes on the derivation of the solution
solution: the word believed to be a solution
"""
def __init__(self,... |
def removeLeading0(string):
split_string = string.split(".")
string = ".".join(str(int(s)) for s in split_string)
return string
ip="192.128.018.011"
print("IP =",ip)
print("with the function:",removeLeading0(ip))
ip="127.0.0.1"
print("IP =",ip)
print("with the function:",removeLeading0(ip))
|
x=2
print('eval(\'x+2\') = ',eval('x+2'))
print('eval(\'pow(x,10)\')) = ',eval('pow(x,10)'))
|
import re
exp = input("Enter a regular expression: ")
count = 0
file = open("mbox.txt")
for line in file:
x = re.findall(exp,line)
if x != []:
count+=1
print("mbox.txt had",count,"lines that matched",exp)
|
def strip_char(string,chs):
return "".join(c for c in string if c not in chs)
string = "Danny is not a dog."
print("string =",string)
strip_string = "aotg"
print("the striped characters:",strip_string)
print("with the function:",strip_char(string,strip_string))
|
import re
def text_match(text):
string = "ab+"
if re.search(string,text):
return "Found a match!"
else:
return "Not matched!"
print(text_match("ab"))
print(text_match("abbc"))
print(text_match("ac"))
|
n = int(raw_input())
on = []
for i in range(n):
name, check = raw_input().split(" ")
if check == 'enter':
on.append(name)
else:
on.remove(name)
on.sort(reverse=True)
for nm in on:
print nm |
import numpy as np
import math
class Windowing:
"""
The window function splits a possibly infinitely long sample stream in
chunks of data. The length of a chunk is windowSize.
"""
def __init__(self, windowSize=4096, stepSize = 2048, windowFunc = np.hamming):
"""
Create a new insta... |
#3) Escreva um programa que leia a quantidade de dias, horas, minutos e segundos do usuário. Calcule o total em segundos.
print("Programa para calcular segundos")
dias = int(input("Digite a quantidade de dias: "))
horas = int(input("Digite a quantidade de horas: "))
minutos = int(input("Digite a quantidade de minutos... |
'''3. João Papo-de-Pescador, homem de bem, comprou um microcomputador
para controlar o rendimento diário de seu trabalho. Toda vez que ele
traz um peso de peixes maior que o estabelecido pelo regulamento de
pesca do estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00
por quilo excedente. João precisa que vo... |
#4. Faça um Programa que leia três números e mostre o maior deles.
print("Digite 3 número e mostraremos o maior deles")
num1 = float(input("Digite o 1º Numero: "))
num2 = float(input("Digite o 2º Numero: "))
num3 = float(input("Digite o 3º Numero: "))
if num1 > num2 and num1 > num3:
maior = num1
elif num2 > num... |
'''Seja o mesmo texto acima “splitado”. Calcule quantas palavras possuem uma das letras
“python” e que tenham mais de 4 caracteres. Não se esqueça de transformar maiúsculas para
minúsculas e de remover antes os caracteres especiais.'''
def tem_python(palavra):
for letra in palavra:
if letra in 'python':
... |
"""
Given a string, find the length of the
longest substring without repeating characters.
"""
def lengthOfLongestSubstring(s):
if s is "":
return 0
longest_substring = 1
temporal_substring = ""
for i in range(len(s)):
if s[i] in temporal_substring:
temporal_substring =... |
class Sudoku:
def __init__(self, data):
self.data = data
def is_valid(self):
if not self.data:
return False
length = len(self.data)
if length**.5 != int(length**.5):
return False
for i in self.data:
if len(i) != length:
... |
"""
Given n non-negative integers a1, a2, ..., an , where each represents a point
at coordinate (i, ai). n vertical lines are drawn such that the two endpoints
of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis
forms a container, such that the container contains the most water.
"""
def maxA... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPRegressor
def MSE(y, yhat):
return np.mean((y - yhat)**2)
def example_data(rows = 100):
x = np.linspace(start=0, stop=30, num = 100).reshape((rows, 1))
#y = 2*np.sin(x) + x
y = np.sqrt(x)
# scale the data
... |
import curses
import time
import random
from collections import defaultdict
from itertools import tee
CONNECTED = {"N": 1, "S": 2, "E": 4, "W": 8}
DIRECTIONS = {"N": (-1, 0), "S": (1, 0), "E": (0, 1), "W": (0, -1)}
ANTIPODES = {"N": "S", "S": "N", "W": "E", "E": "W"}
WALL = {12: '═', 3: '║', 10: '╗', 5: '╚', ... |
"""
Karis Kim
1624226
CIS 2348
"""
def selection_sort_descend_trace(lst):
for n in range(len(lst) - 1):
largest_value = n
for j in range(n + 1, len(lst)):
if lst[j] > lst[largest_value]:
largest_value = j
lst[n], lst[largest_value] = lst[largest_value],... |
"""
Karis Kim
CIS 2348
1624226
"""
def caroptions():
# options
print("Davy's auto shop services")
print("Oil change -- $35")
print("Tire rotation -- $19")
print("Car wash -- $7")
print("Car wax -- $12")
# setting the prices
oil_change = 35;
tire_rotation = 19;
car_wash = 7;
c... |
"""
Karis Kim
1624226
CIS 2348
"""
numbers = input().split()
noneg_int=[]
for num in numbers:
# Convert the string number into integer.
num = int(num)
# Checks whether number is non-negative.
if num >= 0:
noneg_int.append(num)
noneg_int.sort()
for i in noneg_i... |
"""
% the Set-game.
% In Set, 12 cards are placed on the table.
% Each card has some object(s) depicted. A card has 4 'parameters':
% - number
% - shape
% - filling
% - colour
%
% The objective is to find sets (|set| = 3) of cards that have all of
% these properties the same, or, per property all different. See t... |
def checkWinner(board):
""" Returns true if winner exist
"""
states = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5 ,8],
[0, 4, 8],
[2, 4, 6]
]
# flatten board
flat_board = []
... |
#!/usr/bin/env python3
num = 1000
def main():
for a in range(1,num,1):
for b in range (1,num-1,1):
c = num - a - b
if a**2 + b**2 == c**2:
print(a * b * c)
return
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
def is_pallindrome(i):
str_ = str(i)
str_rev = rev(str_)
return str_ == str_rev
def rev(s):
return s[::-1]
def main():
i=999
j=999
palindromes = []
for m in range(i,100,-1):
for n in range(j,100,-1):
if is_pallindrome(m * n):
... |
#!/usr/bin/env python3
from math import factorial
n = 20
def main():
print (int((factorial(2 * n) / (factorial(n) * factorial(n)))))
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
import re
def parse_data(file):
data_file = open(file, 'r')
data = data_file.read().splitlines()
passports = []
attr = {}
for line_number, line in enumerate(data):
# print(line)
key_value = line.split(' ')
# print(key_value)
for i in key_val... |
# A light weight- python program to count the vote to sum and find the winner
# the length of the file is 803,000
import csv
my_file = "../GWDC201805DATA3-Class-Repository-DATA/03-Python/Resources/election_data.csv"
with open(my_file, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# ... |
# 第五章 クラスの作成/インスタンスの作成/メソッドの利用/継承
class MyObj:
pass
ob = MyObj()
print(type(ob))
# メモクラス (Memo)を作成する
class Memo:
message = "OK"
memo = Memo()
print(memo.message)
memo.message = "Hello!"
print(memo.message)
class MyClass:
message = "OK"
# print関数とは別にここではprintメソッドを定義する
... |
from enum import Enum
import pickle
class ReplayMode(Enum):
WRITE = 1
READ = 2
class Replay:
"""
A class for the record used for the replay.
"""
def __init__(self, seed=None, path=None):
"""
If path isn't None, the replay should load the corresponding file.
Otherwise,... |
import random
from constants import *
class game:
def __init__(self):
self.ball_y = WINDOW_HEIGHT - BALL_RADIUS # y position of ball
self.ball_x = BALL_X_POS # x position of ball
self.y_change = 0 # change in y of the ball
self.score = 0 # score of the game
self.obstacles = ... |
" Step 2: Add drop-downs"
execfile("step0.py")
# How Bokeh interpret all goes in one single document (container)
from bokeh.io import curdoc
from bokeh.layouts import row, column
# Column data source to wrap our data
from bokeh.models import ColumnDataSource
# Select boxes for drop down menu (widget)
from bokeh.model... |
from graphics import*
def askUserColour():
coloursList = []
validColours = ["red", "green", "blue", "magenta",
"cyan", "orange", "brown", "pink"]
while True:
colour = input("Enter a colour for your patch (eg: red, green, " +
"blue, magenta,... |
def get_all_files(path_string):
all_files = []
p = Path(path_string)
for file_or_folder in p.iterdir():
if file_or_folder.is_dir():
print(str(file_or_folder) + " is a folder")
f = Path(path_string + '/' + str(file_or_folder) + '/')
print("reading " + str(f))
... |
#
We now want to count the number of items in the list (6). What do we need to add to the accumulator now?
numbers = [4, 8, 15, 16, 23, 42]
count = 0
for n in numbers:
count = count + __
print(count) |
#
Print the 3x3 identity matrix with nested lists.
identity_3 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
print(identity_3) |
#
Run the code to see what happens when we try to retrieve the length of one number, which is not a list.
Note: First run the code as it is, and only then fix the code by making a list with on element on line 1.
list_of_one = 5
should_be_one = len(list_of_one)
print(should_be_one) |
#
Store 27 in the variable temperature. Line 2 prints the value of temperature so if you fill it correctly it will print 137.
temperature = __
print(temperature) |
#
Some things are wrong with the nested loop. Can you fix it?
suits = ['clubs', 'diamonds', 'hearts', 'spades']
values = ['7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
for suit in suits:
for value in values:
print(value + ' of ' + suit.capitalize()) |
#
<div>We want to use the nested loops to print the cards in order of value, so:
7 of Clubs</div><div>7 of Diamonds
7 of Hearts</div><div>7 of Spades</div><div>8 of Clubs </div><div>...
How should we change the code?</div><div>
</div>
suits = ['clubs', 'diamonds', 'hearts', 'spades']
values = ['7', '8', '9', '10'... |
#
Negative numbers get elements from the end of a list.
Fill the blanks to make the assertEqual's pass.
beatles = ['John', 'Paul', 'George', 'Ringo']
assertEqual(beatles[-1], __)
assertEqual(beatles[-2], __)
assertEqual(beatles[-3], __) |
#
Change line 2 such that the loop prints all numbers again.
But... do not use while odd != []:!
It must be as short as possible!
odd = [1, 3, 5, 7, 9, 11]
while odd == []:
item = odd.pop()
print(item) |
#
class AboutSets(unittest.TestCase):
def test_set_have_arithmetic_operators(self):
beatles = {'John', 'Ringo', 'George', 'Paul'}
dead_musicians = {'John', 'George', 'Elvis', 'Tupac', 'Bowie'}
great_musicians = beatles | dead_musicians
self.assertEqual(__, great_musicians)
... |
#
Indeed, translation can be created with a dictionary. In this first step we create the dictionary and retrieve an item.
Can you finish the code?
calculations_to_letters = __ #<-- create the dictionary here
one_in_letters = __ #<-- loop up '1' here
print(one_in_letters)
plus_in_letters = __ #<-- loop up '+' here
pr... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 wmsj100 <wmsj100@hotmail.com>
#
# Distributed under terms of the MIT license.
"""
"""
def power1(m,n):
result = 1
for i in range(n):
result *= m
return result
def power2(m,n):
if n == 0:
return 1
... |
def cal(p1, p2, *nums):
print nums
sum = p1**2 + p2**2
for num in nums:
sum += num**2
return sum
print cal(1,2, 4,5)
def cal1(p1,p2,**args):
print args
cal1(1,2,name='wmsj',age=12) |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 ubuntu <ubuntu@VM-0-13-ubuntu>
#
# Distributed under terms of the MIT license.
"""
"""
class People:
def __init__(self, name):
self.name = name
def say(self):
print("I am people {}".format(self.name))
class... |
#import statements and variables
import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':1... |
class Stack:
def __init__(self):
self.size = 0
self.list = []
def isEmpty(self):
return self.size == 0
def push(self, data):
self.list.append(data)
self.size+=1
def pop(self):
self.list.pop()
self.size-=1
def peek(self):
return self.lis... |
'''
1.) swapping two variables
2.) Fibonacci Sequence
'''
a = 5
b = 10
print(a,b)
temp = 0 #temporary variabale is created
temp = a #temporary variable is used to save value of a
a = b #value of b is given to a
b = temp #b recieves previous value of a via temp
print(a,b)
print()
#WHILE LOO... |
'''
Operations with Lists
Keyewords : addition(conactenate), slices, deleting(removing) elements
Gerardo Riverra
12-6-18
'''
from gerardolib import fibon_sequence
alist = ["a", "b", "c", "d", "e"]
blist = ["v", "w" ,"x", "y", "z"]
# Concatenation
print(alist + blist)
print(alist)
# slicing lis... |
#!/usr/bin/env python3
"""
--- Day 6: Memory Reallocation ---
"""
memory_banks = '4 10 4 1 8 4 9 14 5 1 14 15 0 15 3 5'.split('\t')
debug_input = [0, 2, 7, 0]
""" Execution of a weirdly-changing program counter """
def string(lst):
""" Not ''.join, because then [12,3] == [1,2,3] collision happens."""
retu... |
#!/usr/bin/env python3
"""
--- Day 1: Inverse Captcha ---
"""
input_file = 'input_day1.txt'
def get_input():
with open(input_file, 'r') as f:
return f.read().strip()
def compute_half_circular(input_code, step):
result = 0
size = len(input_code)
# step = size / 2
for i, ch in enumerate(... |
#!/usr/bin/env python3
"""
--- Day 5: A Maze of Twisty Trampolines, All Alike ---
"""
input_file = 'input_day5.txt'
def get_input():
# test input:
# return [0, 3, 0, 1, -3]
with open(input_file, 'r') as f:
return f.readlines()
def out_of_range(index, size):
return index < 0 or index >= si... |
def main(): #主函数定义在前,增加可读性
message()#程序解释
dic = build_dic()#创建字典
active = 1 #程序运行状态选项
while active != 0:
bar()
user_in = input("1,查询,2,增加,3,删除,0,退出:")
if is_number(user_in) == True : #判断输入的是不是一个数字
user_inf = float(user_in)
active = int(user_inf)
if float(active) != user_inf or len(user_in) != 1 :
... |
import math
class Location:
def __init__(self, x, y):
self.x = x
self.y = y
self.xi = int(math.floor(x))
self.yi = int(math.floor(y))
def distance_euclidean(l1, l2):
x2 = math.pow(l1.x - l2.x,2)
y2 = math.pow(l1.y - l2.y,2)
return math.sqrt(x2 + y2)
def distance_manh... |
#Gets the data from the Olympics.txt file and puts them into two lists,
#one for the year of the Olmypics and one for the place the games took place.
#Return : yearList, placeList
def getData():
olympData = open("Olympics.txt", 'r')
yearList = []
placeList = []
curLine = olympData.readline()
... |
if __name__ == '__main__':
# Create an array for the counters and initialize each element to 0.
from array import Array
theCounters = Array(127)
# Open the text file for reading and extract each line from the file
# and iterate over each character in the line.
theFile = open("C:/temp/atextfile.... |
# written by Christopher Shanor
# cshanor@zoho.com
from tkinter import *
window = Tk()
def convert():
grams = float(e1_value.get()) * 1000
lbs = float(e1_value.get()) * 2.205
oz = float(e1_value.get()) * 35.274
t1.insert(END, grams)
t2.insert(END, lbs)
t3.insert(END, oz)
l1 = Label(window, t... |
#Creating and instantiating python classes
#classes - they allow us to logically group data(attributes) and functions (methods)
'''class Employee:
pass
print ("Class (Blueprint) vs Instance")
emp1 = Employee()
emp2 = Employee()
print (emp1)
print (emp2)
print ("instance variables contains data unique to each insta... |
# Para obtener ciertas estadísticas de un recorrido, se pide realizar un
# y en metros por segundo. programa que dada una distancia, entregue la
# velocidad en kilómetros por hora. Para esto, existen dos variables tiempo
# y distancia que vienen en segundos y kilómetros respectivamente. Tu programa
# debe guardar en l... |
import cv2
import matplotlib.pyplot as plt
import MaxPool
import ConvOp
import Activations
import sys
# Using sys.stdout to print the output of this script to a text file
sys.stdout = open("CNN_from_Scratch_output.text", "w")
# Reading a sample image to test our implementation of Convolutional Neural Network
sample_i... |
# Lukas Schwab, 6/15/14
# github.com/lukasschwab
# lukas.schwab@gmail.com
#-----------------------#
# Defines a color as a weighted average between two, input as a percentage.
#-----------------------#
# Prompt the two color inputs
clr0=raw_input('Enter the hex value for the 0 percent color. ')
clr100=raw_input... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.