text stringlengths 37 1.41M |
|---|
import random,sys
from io import StringIO
def mazeGen(rows,cols):
try :
rows -= 1
cols -= 1
except (ValueError, IndexError) :
print("2 command line arguments expected...")
print("Usage: python maze.py rows cols")
print(" minimum rows >= 10 minimum cols >= 20")
qu... |
import sqlite3
def create_database():
sqlite_file= 'databases.db'
table_name= 'users'
id_column= 'id_column'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
# c.execute('''DROP TABLE IF EXISTS users''')
c.execute('''CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY AUTOINCREMEN... |
import pandas as pd
if __name__ == "__main__":
data = pd.read_csv("data/CRDC2013_14.csv", encoding="Latin-1")
races = ["HI", "AM", "AS", "HP", "BL", "WH", "TR"]
genders = ["F", "M"]
data["total_enrollment"] = data["TOT_ENR_M"] + data["TOT_ENR_F"]
all_enrollment = data["total_enrollment"].... |
#Made on May 27th, 2017
#Made by SlimxShadyx
#Editted by CaptMcTavish, June 17th, 2017
#Dice Rolling Simulator
import random
global user_exit_checker
user_exit_checker="exit"
def start():
print "Welcome to dice rolling simulator: \nPress Enter to proceed"
raw_input(">")
result()
def bye():
print "... |
from os.path import join, isfile
from os import listdir
src_dir_ = 'original_size'
def count_files(src_dir):
dirs = [folder for folder in listdir(src_dir) if not isfile(join(src_dir, folder))]
count = 0
for dir_ in dirs:
dir_ = join(src_dir, dir_)
classes = listdir(dir_)
for class_... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 09:39:43 2019
@author: HP
"""
def swap(a,b):
temp=arr[a]
arr[a]=arr[b]
arr[b]=temp
def InsertionSort():
for i in range(1,len(arr)):
j=i
while(arr[j-1]>arr[j] and j-1>=0):
swap(j-1,j)
j=j-1
arr=[5,7,8... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 17:19:11 2019
@author: HP
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 16:50:16 2019
@author: HP
"""
#class Node1:
# def __init__(self,data):
# self.key=data
# self.next=None
#
class Node:
def __init__(self,data):
self.ke... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 12:12:41 2019
@author: HP
"""
x=[3,4,5,2,1]
print(zip(x,range(len(x)))) |
# Dictionaries - a dictionary is an unordered set of key-value pairs
dict1 = {} # creating an empty dictionary
dict1 = {"Vendor": "Cisco", "Model": "2600", "IOS": "12.4", "Ports": "4"}
dict1["IOS"] # returns "12.4"; extracting a value for a specified key
dict1["IOS"] = "12.3" # modifies an existing key-value pair... |
# Todo: Use ABC to do proper abstract classes
class Sync:
"""Defines a process with synchronous characteristics"""
def __init__(self):
# List of modules to clock with this module
self.submodules = []
def clock(self):
"""Handle clocking to define new outputs"""
# By definition... |
from inky import InkyPHAT
inky_display = InkyPHAT("black")
inky_display.set_border(inky_display.WHITE)
from PIL import Image, ImageFont, ImageDraw
img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT))
draw = ImageDraw.Draw(img)
questions = [
["What sweet food made by bees using nectar from flowers... |
# dictionary comprehension
square_value_dict = { x:x**2 for x in range(10) }
# expected output:
'''
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
'''
print( square_value_dict ) |
sec_per_min = 60
min_per_hour = 60
hour_per_day = 24
seconds_per_hour = sec_per_min*min_per_hour
# How many seconds are there in one hour?
print( seconds_per_hour ) |
total = ['item_one', 'item_two', 'item_three', 'item_four', 'item_five']
print(len(total))
str1 = '联系'
print(str1)
print(str1 + "您好")
import sys
x = 'runoob'
sys.stdout.write(x + '\n')
x="a"
y="b"
print(x, end=".")
def a():
'''这是注释'''
pass
print(a.__doc__)
languages = ["C", "C++", "Perl", "Python"]
for x... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def count(self, search_for):
current = self.head
count = 0
while(current is not None):
if curr... |
# engrjepmanzanillo
class Solution:
def __init__(self, string):
self.string = []
for i in range(len(string)):
self.string.append(string[i])
self.reversed_string = self.string[::-1]
def isPalindrome(self):
if self.string == self.reversed_string:
if len(s... |
#Async code
#Async runs in the same thread
'''
Async uses CoRoutines which run on the same thread
"async" and "await"
'''
import logging
import multiprocessing
import threading
import time
import asyncio
import random
logging.basicConfig(format='%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s', date... |
# Multiple Inheritance
# inherit from multiple classes
class Vehicle:
speed = 0
def drive(self, speed):
self.speed = speed
print(f'Driving')
def stop(self):
self.speed = 0
print(f'Stopped!')
def display(self):
print(f'Driving at {self.sp... |
# imports:
import json
import os.path
# Inventory Class:
class Inventory:
pets ={}
def __init__(self):
self.load()
def add(self, key, qty):
q = 0;
if key in self.pets:
v = self.pets[key]
q = v + qty
else:
q = qty
... |
import random
def rolldice(): #this function generates three random numbers and returns them in an array
values = []
i = 0
while i < 3:
values.append(random.randrange(1,6))
i = i + 1
return values
#This is a mess off booleans that keeps calling rolldice() until a pair is noticed the... |
# WRITE YOUR FUNCTIONS HERE
def get_pet_shop_name(pet_shop):
return pet_shop["name"]
def get_total_cash(pet_shop):
return pet_shop["admin"]["total_cash"]
def add_or_remove_cash(pet_shop, num):
pet_shop["admin"]["total_cash"] += num
def get_pets_sold(pet_shop):
return pet_shop["admin"]["pets_... |
"""This file defines a simple framework for hyper-parameter tuning.
It takes the input as a json fine which has a dictionary of hyper-parameters
to be tuned along with the list of values for that hyper-parameter.
All combinations of the hyperparameter values are run and result and checkpoints
are stored in a separate... |
# if Statement
# if 10 > 5:
# print('10 greather then 5')
# print('if scope finished')
# print('Close Program')
# nested if
# if 10 > 5: condition True
# print('10 greather then 5')
# if 8 > 5: condition True
# print('8 greather then 5')
# print('Program closed')
# if 10 > 5: Condition Tr... |
# exception
# user_number_a = int(input('Enter Number of A : '))
# user_number_b = int(input('Enter Number of B : '))
# result = user_number_a/user_number_b
# print(result)
# try:
# user_number_a = int(input('Enter Number of A : '))
# user_number_b = int(input('Enter Number of B : '))
# result = user_nu... |
from random import randint
games = {}
winners = {}
player = {'name': 'name', 'health': 100, 'heal': 2}
monster = {'name': 'Learning-to-Code', 'health': 100}
print(' ')
print('>' * 28 + ' STARTING THE GAME ' + '<' * 28)
print('Welcome to the Learning-to-Code Monster Game')
print('... based on real life events of a Re... |
# implement of renderers
#
# renderer solves if in any case that you want to show the string in a box.
class Renderer:
def __init__(self, height, width, **render_styles):
# in order to access the attributes of the instance
# which this renderer belong to.
self._render_styles = render_sty... |
from datetime import datetime
import time
def partition(limit):
u_limit_list = []
l_limit_list = []
for i in range(1,limit):
mid = limit/2
if(i >= mid):
u_limit_list.append(i)
elif(i < mid):
l_limit_list.append(i)
return (u_limit_list,l_limit_list)
... |
import re
import os
# Author: Huang Jian Wei
# Date Created: 08/11/2019
# Date Last Modified: 11/11/2019
result_file = open("result.txt", "a+")
def main():
while 1:
user_input = input("(1) for single file, (2) for directory,"
"(3) to exit:""\n1.) File\n2.) Directo... |
# Even though there are multiple objects, we still only need one class.
# No matter how many cookies we make, only one cookie cutter is needed.
class Car(object):
# The Constructor is defined with arguments.
def __init__(self, c, xpos, ypos, xspeed):
self.c = c
self.xpos = xpos
self.ypos = ... |
# Определение количества различных подстрок с использованием хеш-функции. Пусть дана строка S длиной N. Например,
# состоящая только из маленьких латинских букв. Требуется найти количество различных подстрок в этой строке. Для решения
# задачи рекомендую воспользоваться алгоритмом sha1 из модуля hashlib или встроенную ... |
# В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
import random
start = int(input('Введите начало диапазона,из которого необходимо генерировать числа: '))
finish = int(input('Введите конец этого диапазона: '))
quantity = int(input('Введите количество чисел,которые необходимо сген... |
x1 = float(input('Введите координату х первой точки : '))
y1 = float(input('Введите координату y первой точки : '))
x2 = float(input('Введите координату x второй точки : '))
y2 = float(input('Введите координату y второй точки : '))
if x1 != x2:
k = (y1-y2)/(x1-x2)
b = y2-k*x2
print(f'y = {k:.3f}*x +{b:.3f}... |
from PIL import Image, ImageDraw, ImageFont
import math
#this turns polar coordinates to cartesian form
def polar_to_cartesian(angle,radius):
angle_radians = math.radians(angle)
x_coord = radius*math.cos(angle_radians)
y_coord = radius*math.sin(angle_radians)
if angle == 0:
y_coord = 0
eli... |
# dict
mystuff = {'apple': "I AM APPLES!"}
print(mystuff['apple'])
# this goes in mystuff.py
def apple():
print("I AM APPLES!")
# so I can 'import mystuff.py' and use 'apple' function
import mystuff
mystuff.apple()
# put a variable named tangerine
def apple():
print("I AM APPLES!")
tangerine = "Living reflectio... |
from sys import argv # 没有这行语句
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("How much do you weigh?", end=' ') # 此处有改动,漏了右半边)
weight = input()
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
print() #为了美观,我加上了这行空格
script, filename = arg... |
#这里有一张重要的图片要记,a.test("hello"),Type error ->只需要1个argument,但是给了2个
# 实际上python经常将mystuff.append('hello')转换成append(mystuff,'hello')
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_sutff = ["Day", "Night", "S... |
from evaluate import evaluate_line
from copy import deepcopy
import random
class branch():
def __init__(self, chess, level, color,x,y):
self.chess = chess
self.color = color
self.level = level
self.length = len(self.chess)
self.width = len(self.chess[0])
self.i = x
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import itertools
import random
from collections import Counter
sym = 10 # number of symbols
spc = 4 # symbols per card
class Solution:
def __init__(self):
self.ok = []
self.n = []
self.rnd = [x for x i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import truth_table
import numpy
import math
'''
Gets the corresponding byte array for an x vector for given [i,j] in the Karnough table.
This function is called in every iteration of the Rosenblatt perceptron learning algorithm.
Also inserts a -1 for biaz and... |
#count the number of bits (1's) in a sequence
# For num = 5 you should return [0,1,1,2,1,2].
# example : [0, 1, 10, 110, 100, 101 ]
def countBits(num):
def count(i):
if(i <= 0):
return 0
else:
mod = i % 2
return mod + count(i // 2)
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object): #1->2->3 2
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
""... |
import requests
user_key = "95175c79b787c7dd4265272c6271ae8b" # api_keys
print("1. Cari Restoran") # input untuk mencari resto
print("2. Daily Menu") # input untuk daily menu (hanya tersedia di Prague)
pilih = input("Masukkan pilihan: ")
headInfo = {'user-key':user_key} # headinfo untuk isi headers, bila tid... |
import sys
import utils.inputReaders as ir
print("Day 5 puzzle: Binary Boarding");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#read the file
board_passes = ir.read_oneline_records_as_list_entries(puz... |
import sys
print("Day 6 puzzle: Chronal Coordinates");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
coordinates = []
with open(puzzle_file, 'r') as puzzle_in:
for cur_line in puzzle_in... |
import sys
import utils.locationHelpers as lh
print("Day 22 puzzle: Crab Combat");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
player1_deck =[]
player2_deck = []
with open(puzzle_file, 'r... |
import sys;
print("Day 17 puzzle: Spinlock ");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
offset = 0;
#open file
with open(puzzle_file, 'r') as puzzle_in:
offset = int(puzzle_in.read().strip("\n... |
import sys
print("Day 14 puzzle: Chocolate Charts");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
num_recipes = 0
with open(puzzle_file, 'r') as puzzle_in:
num_recipes = int(puzzle_in.... |
import sys
print("Day 2 puzzle: T1202 Program Alarm");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
instr_list = []
with open(puzzle_file, 'r') as puzzle_in:
instr_list = [int(instr) fo... |
import sys;
import math;
print("Day 3 puzzle: Spiral Memory");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
with open(puzzle_file, 'r') as puzzle_in:
for cur_line in puzzle_in:
me... |
import re;
print("Day 3 puzzle: Squares With Three Sides");
num_triangles = 0;
sequencer = 1;
sides = [[0,0,0],[0,0,0],[0,0,0]];
#open file
with open('./puzzle_input/day03.txt', 'r') as puzzle_in:
for cur_line in puzzle_in:
print(cur_line.strip("\n"));
# split string into array of directions
... |
import sys
import re
print("Day 12 puzzle: Subterranean Sustainability");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
#open file
init_state = [0,0]
game_of_life = {}
with open(puzzle_file, 'r') as pu... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(raw_input())
stack = [];
while n>0:
line = raw_input()
array = line.split()
if array[0] == 'push':
stack.append(int(array[1]))
print stack[len(stack)-1]
elif array[0] == 'pop':
stack.pop()
if len(stack) > 0:
pr... |
from sklearn.metrics import confusion_matrix, mean_squared_error
from sklearn.neural_network.multilayer_perceptron import MLPClassifier
from nn_classification_plot import plot_hidden_layer_weights, plot_histogram_of_acc, plot_images
import numpy as np
__author__ = 'bellec,subramoney'
"""
Computational Intelligence T... |
#!/usr/bin/env python
import sys
import util
numbers = set(util.numbers_from_file(sys.argv[1]))
def find_sum(val):
for n in numbers:
if (val - n) in numbers:
return n, val - n
return None
def product_of_three():
for n in numbers:
result = find_sum(2020 - n)
if result i... |
#!/usr/bin/python
print('Welcome to a fun game of dice!')
print('We call this game 10,000.')
print('Whats your name? You\'ll be player 1')
NAME = raw_input()
print "Nice to meet you", NAME, "you read to play?"
print("first i need to know if your familiar with the rules? (y or n)")
CHOICE = raw_input()
if CHOICE == 'y'... |
import re
pattern = r"eggs"
if re.match(pattern,"moreeggs_extremeeggs"): # match looks for the exact start hence it will return No match found here.
print('Match Found!')
else:
print ('No match found!') |
class MyClass():
__hiddenVariable = 0 # double underscore used to hide the variable, and hence data hiding is done.
def add(self,increment):
self.__hiddenVariable+= increment
print (self.__hiddenVariable)
object = MyClass()
object.add(5)
print (object.__hiddenVariable) #this won't be... |
import re
pattern = r"bread(eggs)*bread"
if re.match(pattern, "breadeggseggsbread"):
print ("Match found")
else:
print ("Sorry") |
#reindexing series and dataframes
from pandas import Series, DataFrame
obj = Series([100,200,300,400,500], index = ['d','a','b','e','c'])
print (obj)
#reindexing Series
obj = obj.reindex(['a','b','c','d','e'])
print (obj)
#----------------------------------------------------------
data = { 'Name' : ['John','Kevin','... |
import numpy as np
#this will divide 10 to 50 in 5 numbers
x = np.linspace(10,50,5)
print (x)
#this won't consider the endpoint i.e. 50 here.
x = np.linspace(10,50,5, endpoint=False)
print (x)
#this will print value of 10 to 100 in equal logarithmic space
a = np.logspace(1.0,2.0,num=10)
print (a)
#this will print t... |
import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print (a)
#integer indexing on multidimensional array
b = a [[0,1,2],[0,1,0]]
print(b) #this will print element 0 from 0th row, element 1 form 1st row and element 0th from 2nd row
x = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
print (x)
row = np.array(... |
"""
Question: Consider a list in Python which includes prices of all the items in a store.
Build a function to discount the price of all the products by 10%.
Use map to apply the function to all the elements of the list so that all the product prices are discounted.
"""
items = [10, 20, 30, 40, 50]
def discount(x):
... |
#----------------------WRITING------------------------------
file = open('demo1.txt', 'w+')
text = input("Enter what you want to write to the file:")
file.write(text)
file.close()
#----------------------READING--------------------------------
file = open('demo.txt', 'r')
print (file.read())
#print (file.rea... |
from pandas import Series, DataFrame
#sorting a series
series_2 = Series([3,7,8,5,6,2],index=[2,3,5,6,7,1])
print(series_2.sort_index())
#sorting a dataframe
data_2 = {'Speed' : [200,300,400],
'Temp' : [35,37,39],
'Humidity': [42,43,45]}
frame_2 = DataFrame(data_2)
frame_2 =frame_2.rein... |
for i in range(1,11):
print (i)
#-----------------------------------------------------------
fruits = ["apple", "banana", "orange", "mango"]
for fruit in fruits:
print (fruit)
#--------------even numbers from 1 to 20---------------------
for e in range (0,21,2):
print(e) |
### import modules ###
import pygame
import random
from random import randint
import Tkinter as tk
from Tkinter import *
from pygame import *
import math
#import datetime
import sys
import time
pygame.init()
######################
### start ###
def start():
print 'welcome to big bad boy braz tower defence game!'
... |
'''
This file is in supplement with ad_rs.py. Here we implement all the problems related to recommender system explained in the ex8.pdf
'''
import numpy as np
import matplotlib.pyplot as plt
from ad_rs import *
# -- READING INPUT DATA
data = read_data('ex8_movies.mat')
# -- Y is a 1682 x 943 matrix, containing ratings... |
'''
Created on Jun 26, 2019
@author: sipika
'''
from Inheritance import MainDemo
class MyClass:
def __init__(self,a,b):
self.a = a
self.b = b
print("Hello Constructor")
def Func(self):
print("My Class Function")
print(self.a,self.b)
var = MyClass(34,'abc')
var.Fun... |
'''
Created on Jul 5, 2019
@author: sipika
'''
from tkinter import *
from tkinter import messagebox
def Go():
from TkinterDemo import NewWin
root.dstroy()
root = Tk()
root.geometry("400x400")
ent = StringVar()
label = Label(root,text="My First Tkinter Demo", bg = "Green", fg="white")
#label.pack(s... |
'''
Created on May 16, 2019
@author: sipika
'''
def is_called():
def is_returned():
print("Hello")
return is_returned
new = is_called()
#Outputs "Hello"
new()
#///////////////////////////////////////////////
def make_pretty(func):
def inner():
print("I got decorated")
func()
... |
'''
Created on May 2, 2019
@author: sipika
'''
str = "I am an Indian"
print(list(str))
list = str.split(" ")
print (list)
for i in range(len(list)-1,-1,-1):
print(list[i].capitalize(), end=" ")
|
# Mini Project 4, Yahtzee Strategy Planner
# Principles of Computing, Part 1
# Jordan Hall
# 09/20/2015
"""
Planner for Yahtzee
Simplifications: only allow discard and roll, only score against upper level
"""
# Used to increase the timeout, if necessary
#import codeskulptor
#codeskulptor.set_timeout(20)
def gen_all_... |
def minmax(a, b):
"return (min(a, b), max(a, b))"
if a <= b:
return (a, b)
else:
return (b, a)
def thisShouldNeverHappen(reason=None):
if reason is None:
reason = "This should never happen"
assert False, reason
def thisIsNotHandled(reason=None):
if reason is None:
... |
# 相加相乗平均 (x+y)/2 >= sqrt(xy) より
# x+y=Aなので A/2 >= sqrt(xy)
# 両辺二乗して (A/2)^2 >= xy
# よって最大値は (A/2)^2
a = int(input())
print((a//2)**2) |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, RobustScaler
from sklearn.linear_model import LinearRegression
from sklearn.feature_selection import SelectKBest, f_regressio... |
#!-*- coding:utf-8 -*-
# __author__ : Sora
# ___time___ : 2019/06/24/15:05
# SECTION 1 - IMPORTS
import networkx as nx
import numpy as np
import random as rd
import matplotlib.pyplot as plt
import warnings
import formula
init_nodes = int(input("Please type in the initial number of nodes (m_0): "))
fina... |
"""
* Написать функцию которая считает кол-во символов в строке, встречающихся более 1 раза
* Вернуть кол-во этих символов
*
"""
import collections
def count_repeated_symbols(s):
count = 0
dict = collections.Counter(s)
for key in dict:
if dict[key] > 1:
count += 1
return count
... |
def main():
#escribe tu código abajo de esta línea
a = int(input())
lista = []
i = 0
if a>0 :
while i<a :
valor = input()
lista.append(valor)
i = i+1
print(lista)
listanodobles = []
for i in lista :
if i not in listano... |
""" My new app
gonna make a lot of $$$
"""
import math
# inherit from object to get additional features
class Circle(object):
""" an advanced toolkit """
version = '0.2'
def __init__(self, radius):
self.radius = radius
# this is cool! do this so you don't expose radius init variable
#... |
"""
https://www.freecodecamp.org/news/python-property-decorator/
"""
class House(object):
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
@price.setter
def price(self, new_price):
if new_price > 0 and isinstance(new_price, float)... |
# Write a program that prints the numbers from 1 to 100.
# For multiples of three, print "Fizz" instead of the number.
# For multiples of five, print "Buzz"
# For multiples of both, print "FizzBuzz"
data = []
n = 0
while n < 100:
n = n + 1
data.append(n)
print data
multiple_of_three = []
for b in data:
if... |
from Queue import *
import copy
from helper import *
def backTrackingSearch(board, theSquares, thePeers):
"""
Wrapper function to house backtracking algorithm.
Returns a solution or failure 'False'.
"""
#Deep copies to avoid altering arguments if BTS is called multiple times
squares = copy.deepcopy(theSquares... |
#料金を計算する関数
def calc(func,arg=1):
price = func(arg)
return price
#子供料金を計算する関数
def child(arg):
return 400 * arg
#大人料金を計算する関数
def adult(arg):
return 1200 * arg
#12歳,3人の料金を計算数する
age = 12
num = 3
if age < 16 :
price = calc(child,num)
else:
price = calc(adult,num)
print(f"{age}歳,{num}人で{price}円です。... |
sum = 50 + 37 + 10
limit = 100
if sum>=limit :
result = "Pass"
else:
result = "Failure"
result += "/" + str(sum-limit)
print(sum)
print("-" * 20)
print(result)
|
numlist = [3, 4.2, 10, "x", 1, 9]
sum = 0
for num in numlist:
if not isinstance(num, (int,float)):
print(num, "数値ではない値が含まれていました。")
break
sum += num
else:
print("合計", sum) |
from random import randint
miss = 0
correct = 0
print("問題!3回間違えたら終了。qで止める")
while miss<3:
a = randint(1,100)
b = randint(1,100)
ans = a + b
question = f"{a} + {b}は?"
value = input(question)
if value == "q":
break
if value == str(ans):
correct += 1
print("正解です!")
... |
import time
def run(bridge, duration=15, delta=1, delay=0):
'''Fade down the light at a specified delay.
Keyword arguments:
bridge -- the bridge that will be controlled (required)
duration -- length of time the effect will last (default 15)
delta -- amount of change between colors (default 1)
... |
import crypt
import string
def brute():
file= open('passwd','r')
line = file.readline()
line = line[:-1]
line = line.split(":")
for i in string.ascii_lowercase:
for j in string.ascii_lowercase:
for k in string.ascii_lowercase:
if crypt.crypt(i+j+k,line[1]) == lin... |
def find_diff(current_word, next_word):
cost = 0
x = 1
d = dict()
e = dict()
alphabet = list('abcdefghijklmnopqrstuvwxyz')
for i in alphabet:
d[i] = x
x += 1
return min(abs(d[current_word] - d[next_word]), 26 - abs(d[current_word] - d[next_word]))
de... |
n = input()
n = list(input())
if n.count('A') > n.count('D'):
print("Anton")
elif n.count('A') < n.count('D'):
print("Danik")
else:
print("Friendship") |
fruit = 'banana'
letter = fruit[1]
length = len(fruit)
last = fruit[length-1]
# print(letter)
# print(length)
# print(last)
# print(fruit[-1])
# 6.3 pg. 68
# index = 0
# while index < len(fruit):
# letter = fruit[index]
# print(letter)
# index = index+1
# print('-------')
# Exercise 6.1 pg.68
# in... |
# Ex 5.1 pg. 65
def user_input():
try:
user_input = input('Enter a number: ')
if user_input == 'done':
return user_input
return float(user_input)
except ValueError as err:
raise ValueError('Invalid input')
total = 0.0
average = 0.0
count = 0
while True:
try:... |
# 11 Regular Expressions pg. 129
import re
# fhand = open('./files/mbox-short.txt')
# for line in fhand:
# line = line.rstrip()
# if re.search('^From:', line):
# print(line)
# 11.1 Character matching in regular expressions pg. 130
# fhand = open('./files/mbox-short.txt')
# for line in fhand:
# ... |
from itertools import permutations, combinations, combinations_with_replacement
lst = [1, 2, 3]
# perm = permutations(lst)
perm = permutations(lst, 2)
for i in list(perm):
print(i)
print('\n\n')
comb = combinations(lst, 2)
for i in list(comb):
print(i)
print('\n\n')
comb = combinations_with_replaceme... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 1 21:55:46 2015
@author: Imanol
This code implements PSRL for the chain problem.
1-2-3-4-5-...-H
Where there is a positive reward only at the last state.
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 1 10:53:57 2015
@author: Imanol
"""
import numpy as np
import ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 1 10:53:57 2015
@author: Imanol
This code implements UCRL for the chain problem.
1-2-3-4-5-...-H
Where there is a positive reward only at the last state.
"""
import numpy as np
import scipy.optimize as op
import random
import matplotlib.pyplot as plt
#-----------------... |
import csv
import sys
from util import Node, StackFrontier, QueueFrontier
# Maps names to a set of corresponding person_ids
names = {}
# Maps person_ids to a dictionary of: name, birth, movies (a set of movie_ids)
people = {}
# Maps movie_ids to a dictionary of: title, year, stars (a set of person_ids)
movies = {}
... |
def is_isomorphic(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
tmp_dict = dict()
tmp_set = set()
for i in range(len(s)):
if s[i] not in tmp_dict:
if t[i] in tmp_set:
return False
tmp_di... |
"""Vertex and Graph Classes for a directed graph"""
class Vertex:
"""
class to keep track of vertices in a graph and their associated edges
"""
def __init__(self, key):
"""
initialize vertex with id number and empty dictionary of edges
"""
self._id = key
self._c... |
"""
Simple breadth first search function
"""
import graph_class
class BfsVertex(graph_class.Vertex):
"""
Minor class adjustments to make BFS work better
"""
def __init__(self, vertex_id, edges=None):
"""
Adapt base class setup to make _node_id a list of lists:
[[node_id, expl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.