text stringlengths 37 1.41M |
|---|
# coding: utf-8
# In[1]:
get_ipython().magic('matplotlib inline')
import random
import numpy as np
import matplotlib.pyplot as plt
# Logistic regression is a supervised learning (has labeled data as input) algorithm for classification. The algorithm is fed with samples - with multiple features and it's correspon... |
import time, QLearning, Map
def main():
## print ' -'*(21)
## map1 = Map.Map("chosen_map_1",True)
## map2 = Map.Map("chosen_map_2",True)
## map3 = Map.Map("chosen_map_3",True)
## print ' -'*(21)
##
## map1.printMap()
## map2.printMap()
## map3.printMap()
## running = False
##... |
# coding: utf-8
# In[80]:
import sys
data1 = [['a', 'k'], 'q', ['t', 'r', 'o'], ['p', 'e']]
#check if there is any list
def is_list(data):
for item in data:
if isinstance(item, list):
break
return True
def count_lists(data):
count = 0
for item in data:
if isins... |
a = "_________"
hod = 0
count = 0
q = [x for x in a]
print('---------')
print('| {0} {1} {2} |'.format(q[0], q[1], q[2]))
print('| {0} {1} {2} |'.format(q[3], q[4], q[5]))
print('| {0} {1} {2} |'.format(q[6], q[7], q[8]))
print('---------')
while True:
b = input()
z = "".join(b.split())
if n... |
x = set(int(i) for i in input().split())
y = set(int(i) for i in input().split())
q = list(x.intersection(y))
q.sort()
for i in q:
print(i, end = " ") |
x = input().split()
q = 0
for i in x:
if i != "0":
print(i, end = " ")
q += 1
for i in range(q, len(x)):
print("0", end = " ") |
#!/usr/bin/python
story = ['Rahul', 'is', 'going', 'to', 'marry', 'sowmya']
story1 = ['on',12,2018]
#print story[0:6]
#print story1[0:3]
#print story[0][4][5]
print story[0]
print story[-2]
print story[-1]
print story[-2][2:5]
print story1[-3][1]
story1[1]=21
print story1[1]
story.append("and");
print story
|
# On second thought, I don't think I can make this. I'll try though.
alphabet = (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)
guess_count = 0
guess_limit = 5
def rand_letter():
randindex = randint(1, 26)
letter = alphabet[letter - 1]
return letter
answer = rand_letter()
answer... |
import time
import bibliotecaDamaChinesa
def menuInicial(): # GUI
limparTela()
print("|"+"="*148+"|")
print("|"+"="*148+"|")
print("|"+"="*70+" Tabuleiro "+"="*67+"|")
print("|"+"="*148+"|")
print("|"+"="*148+"|")
print("\n"*4)
tabuleiro = bibliotecaDamaChinesa.criarTabuleiro()
imprimirTabuleiro(tabuleiro) ... |
# 溢出判断
# 全零
def helper(nums):
n =len(nums)
flag = 1
for i in range(n-2, -1, -1):
if flag:
dic = []
for pos in range(i+1, n):
dic.append((nums[pos], pos))
dic = sorted(dic)
for j in range(len(dic)):
if nums[i]<dic[j][0]:
... |
import sys
import csv
#function to find substring from a string between two given substrings
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
#open file given at comman... |
class Directorio:
def __init__(self):
self. _NombreDir = "" # Nombre del directorio
self._InodoDir = 0 # Inodo del directorio
self._Libre = True # Estado del directorio 0 si no existe ese, 1 si ya existe self. _Inodos = [] # Inodos de los archivos que guarda este directorio
... |
word = "hangman"
y = ''
turns = 8
while turns > 0:
failed = 0
# Print the words that contain in word put in y
for i in word:
if i in y:
print(i, end=' ')
else:
print("_", end=' ')
failed += 1
# If u have all word == Win
if failed == 0:
prin... |
from proj_eul.string_tools.tools import insert as _insert
def is_pandigital(n, digits = 9):
li = [i for i in str(n)]
# print li, len(li)
for i in range(1, digits + 1):
# print i, str(i) in li
if not str(i) in li:
return False
return True
def pandigitals(digits):
if digi... |
# Encryption class for encrypting login info
from Crypto.Cipher import AES
import base64
import os
import hashlib
import binascii
class LoginEncoding:
def __init__(self, username, password):
self.username = self.loginEncryption(username)
self.password = self.passwordHashing(username, password)
... |
'''
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
'''
#Solution: All power of two numbers have only one bit set.
class Solution:
def isPower... |
#!/bin/python3
import math
import os
import random
from random import shuffle
import re
import sys
def print_board(board):
for r in board:
for c in r:
print(c, end='')
print("")
def nextMove(player, board):
available = []
for i1 in range(3):
for i2 in range(3):
cell = board[i1][i2]
if cell != 'X' ... |
#!/bin/python
from random import randint
import time
def createGrid(n, m, input):
if n*m == len(input):
grid = []
ini = 0
fini = m
while fini <= len(input):
grid.append(input[ini:fini])
ini+=m
fini+=m
return grid
else:
return None
def printGrid(grid):
for r in range(0, len(grid)):
for c in r... |
'''The python code is used to solve protein-folding problem in Assignment 1
of COMP 557.
Protein-folding problem requires to find the folding structure of a given
protein sequence with minimum free energy.
Protein-folding problem is an NP problem. Although the algorithm makes use
of symmetry to reduce search space ... |
# PLANNING
# Write a program to play Rock Paper Scissors with a user
# Flesh out the plan and think how this gonna work
# Rules:
# Rock > Scissors
# Scissors > Paper
# Paper > Rock
import random
wins = 0
losses = 0
ties = 0
# Start up the program
start = input('Ready to play the game?\n [y] Yes [n] No: '... |
import time
class Timer:
def __init__(self):
self.start = 0.0
def __enter__(self):
self.start = time.time()
def __exit__(self, exc_type, exc_val, exc_tb):
end = time.time()
print("elapsed", end - self.start, "s")
|
# Import the libraries i'm gonna need for creating the GUI..
# ..and downloading the YouTube videos
import tkinter as tk
import tkinter.font as font
from tkinter import *
from tkinter import messagebox, filedialog
from pytube import YouTube
from moviepy.editor import *
# Creating Widgets function
def Widgets():
#... |
n1 = int(input('Numero 1: '))
n2 = int(input('Numero 2' ))
print(n1+n2)
|
import random
path="C:\Users\HP\Documents\list_of_words.txt"
l=[]
with open(path) as f:
content=f.read().split('\n')
f.close
d=len(content)
for i in range(0,d):
if(len(content[i])>=0):
l.append(content[i])
#print l
d=len(content)
word=l[random.randint(0,d-2)]
print word
lengt... |
#!/usr/bin/env python3
"""
The basics of async
"""
import asyncio
import random
async def wait_random(max_delay: int = 10) -> float:
"""
waits for a random delay between 0 & "max_delay" seconds then returns it
"""
rend = random.uniform(0, max_delay)
await asyncio.sleep(rend)
return rend
|
# Find the unique number - Solved 2/7/2020
# https://www.codewars.com/kata/585d7d5adb20cf33cb000235/train/python
# Instructions:
# There is an array with some numbers. All numbers are equal except for one. Try to find it!
# find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
# find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
# It’s guarante... |
# Sum of Digits / Digital Root - Solved 2/13/2020
# https://www.codewars.com/kata/541c8630095125aba6000c00/train/python
# Instructions:
# In this kata, you must create a digital root function.
# A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n.
# If that valu... |
class Node:#create class to contain values
def __init__(self, val):
self.value = val
def __hash__(self):#make node hashable in dictionary
return hash(id(self))
def __eq__(self, other):
return (id(self) == id(other))
def __ne__(self, other):
return not(id(self) == id(... |
"""
Know more, visit my Python tutorial page: https://morvanzhou.github.io/tutorials/
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
Dependencies:
tensorflow: 1.1.0
這是修訂版的第一課,先介紹 tf 的 constant ,這個教法很好。
"""
import tensorflow as tf
import pdb
m1 = tf.constant([[2, 2]])
m2 = tf.constant([[3],
... |
#!python
from __future__ import division, print_function # Python 2 & 3 compatibility
from random import randint
class Listogram(list):
"""Listogram is a histogram implemented as a subclass of the list type"""
def __init__(self, word_list = None):
"""
Initializes histogram as a new list and g... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Imports
import re
import os
import time
import shutil
import curses
import subprocess
import commands
import tarfile
class ProgressBar:
""" Creates a text-based progress bar. Call the object with the `print'
command to see the progress bar, which looks somethin... |
#Spencer Zahn - Python lesson 2 - Exercise 3 - 013118
#Exercise 3: Write a program to prompt the user for hours and rate per hour to compute gross pay.
#Enter Hours: 35
#Enter Rate: 2.75
#Pay: 96.25
x = float(input("Enter Hours: "))
y = float(input("Enter Rate: "))
z = x*y
print ("Pay: " + str(z))
|
from random import randint
def greet():
print("-------------------")
print(" Приветсвуем вас ")
print(" в игре ")
print(" крестики-нолики ")
print("-------------------")
print(" формат ввода: x y ")
print(" x - номер строки ")
print(" y - номер столбца ")
def show():
... |
import numpy as np
def linear_activation(W, b, X):
z = np.dot(W.T,X) + b
return z
def sigmoid(z):
'''
Returns sigmoid activation for array z
'''
a = 1. / (1. + np.exp(-z))
return a
def backward_propagation(A, X, Y):
m = X.shape[1]
dz = A - Y
dW = np.dot(X, dz.... |
import random
class Card(object):
#this class deck will represent the uno card class
cardColor = ['Red', 'Yellow', 'Green', 'Blue']
cardNumber = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#TODO: Add wilds, skip, reverse and draw X card cards
def __init__(self, color , number):
self.color = color
... |
## Dictionary
print('==============================================================')
name = 'Angshu'
a = {
'name': name,
'age': 30,
'address': 'sodepur',
123: 'ABCD'
}
print(a)
print(type(a))
print(a['name'])
print(a[123])
#print(a.name) # this will cause error
print('Printing all the keys')
for key i... |
# basic function with input arguments and single return
print('==============================================================')
def getWelcomeMessege(name='Anonymus', surname='', age=' '):
outputString = f"""
Hi {name} {surname}. You are {age} year old.
"""
return outputString
output = getWelcomeMe... |
## concatination strings from a list
print('==============================================================')
a = ['string1', 'string2', 'string3', 'string4', 'string5']
print(a[0],a[1], sep='+') # '+' will act as separetor
print('==============================================================') |
print('==============================================================')
class MyClass:
memberVariable1 = None
def __init__(self):
self.memberVariable1 = 'basic value'
def display(self, userGivenValue=None):
if userGivenValue != None:
self.memberVariable1 = userGivenValue
... |
import numpy as np
from matplotlib import pyplot as plt
#training set
datasetxor = np.array([
[0,0,0],
[0,1,1],
[1,0,1],
[1,1,0],
]);
def sigmoid(val):
res = 1/(1+np.exp(-val));
return res;
def predict_xor(row, w):
activation = w[0];#for bias
for i in range(len(ro... |
import heapq
class PriorityQueue:
def __init__(self):
self.elements = []
def empty(self):
return len(self.elements) == 0
def put(self, item, priority):
heapq.heappush(self.elements, (priority, item))
def get(self):
return heapq.heappop(self.elements)[1]... |
x=int(input("Enter value of x"))
l=[x+x*x+x*x*x for x in range(1,x+1)]
print(l)
|
# ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. 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 function should return the string
# 'fail'
... |
import Encrypter
import User
import CheckMail, CheckSms
import os, time
import getpass
import GenerateSalt
import db
def signup():
while True:
print("Please Enter Your UserName")
username = input()
os.system("cls")
if User.check_user(username):
print("User AlreadY Exist... |
# The data we need to retrieve.
# 1. The total number of votes cast
# 2. A complete list of candidates who received votes
# 3. The percentage of votes each candidate won
# 4. The total number of votes each candidate won
# 5. The winner of the election based on popular vote.
# Add our dependencies.
import csv
import os... |
from pprint import pprint
from Hashon import Encoder
from Game import Game
question = input("What do you want to do: ")
list_of_hashes = []
if question == "hash":
code = input("Code: ")
hasher = Encoder(code, list_of_hashes)
hasher.encode()
elif question == "list of hashes":
if list_of_hashes:
pprint(list_o... |
# Python Program to Merge Two Lists and Sort it
list1 = []
list2 = []
a = int (input('Enter the range : '))
for i in range(1,a):
num1 = int (input('Enter number : '))
list1.append(num1)
b = int (input('Enter the range : '))
for i in range(1,a):
num2 = int(input('Enter number : '))
list2.append(num2)
... |
def sort_list(list):
list.sort(key = len)
return list
list = ['amar','darshan','rushikesh','bunty','raj','nehal','santosh']
print(sort_list(list)) |
lst = []
l = int(input("enter the length of list : "))
for i in range(l):
n = int(input('Enter the number : '))
lst.append(n)
print('Before sorting elements : ',lst)
for i in range(len(lst)):
for j in range(len(lst)):
if lst[i] >= lst[j]:
temp = lst[i]
lst[i] = lst[j]
... |
### Create a program for a small buisiness.
### The program should help manage tasks assigned to each memeber of the team
### Create username and password text file
### Create Task text file
userfile = open("user.txt", "w+")
tasks = open("tasks.txt", "w+")
### Set admin name and password to admin, adm1n
name = user... |
import numpy as np
#create numpy array
a = np.arange(9)
a
#get the element from array with index 5
a[5]
#get elements from 0 to 4
a[0:5]
#get last but one element
a[-2]
#get elements from 6 to 8
xy = a[6:9]
xy
#reshape the array to 3 by 3
a = np.arange(9).reshape(3,3)
a
#get element with ind... |
a = input("알파벳을 입력하세요 : ")
if a == "a" or a == "e" or a == "i" or a == "o" or a == "u":
print("%s (은)는 모음입니다." %(a))
else:
print("%s (은)는 자음입니다." %(a)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from math import sqrt
import random
def integer_sqrt(x:int):
"""
Return the integer part of the square root of x, even for very large integer values.
Python 'math' module does not operate as expected for large integers.
Got from https://stackoverflow.com... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ressources.multGroup as multGroup
import ressources.utils as ut
import ressources.interactions as it
import random as rd
#
# Diffie–Hellman key exchange is a method of securely exchanging cryptographic keys over a public channel
#
##### - Normal DH
# 1)
def ag... |
from os import name, system
class Match:
"""Class handling match logic"""
def __init__(self):
self.round = 0
self.result = ''
self.log = []
def save_log(self, user_play, com_play):
"""Saves round to log"""
tmp_log = {
'Round': self.get_round(),
'User': user_play,
'Com': com... |
# The "for" loop
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
for x in range(5):
print(x) # Prints out the numbers 0,1,2,3,4
for x in range(3, 6):
print(x) # Prints out 3,4,5
for x in range(3, 8, 2):
print(x) # Prints out 3,5,7
# "while" loops
count = 0
while count < 5:
print(cou... |
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
aggregate = 0
counter = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"):
continue
aggregate += float(line[19:])
counter += 1
avg = aggregate / counter
print('Average spam conf... |
from math import ceil
path = 'D:\\Training\\python-training\\CS101\\'
tpmon_file = open(path + 'tpmon.txt')
# read all lines and store it in a list
monthly_temperatures = tpmon_file.readlines()
# clean up each item and make sure all items are string
monthly_temperatures = [temps.strip() for temps in monthly_temperat... |
name = input("Enter file:")
if len(name) <1:
name = "mbox-short.txt"
handle = open(name)
email_counts = {}
for line in handle:
if line.startswith('From '):
words = line.strip().split()
email = words[1]
email_counts[email] = email_counts.get(email, 0) + 1
biggest_count_email = None
b... |
Celcius = int(input("Wpisz temperature w celciuszach: "))
Farenheit = 9.0/5.0 * Celcius + 32
print("Temperature:", Celcius, "Celcius =", Farenheit, " F") |
import turtle
import random
import math
import time
from random import uniform
# create screen
win = turtle.Screen()
win.title('Hungry Turtle')
win.bgcolor('lightpink')
win.tracer(3)
# instructions for game
instructions = turtle.Turtle()
instructions.color('white')
instructions.penup()
instructions.hideturtle()
inst... |
"""
SOURCE:
Mind of Douglas Adams
DESCRIPTION:
Check a list of lists to make sure they are all the same length
if same lengths return true
if not return false
ARGS:
CheckArguments
Type:
python boolean
Description:
if true, checks the arguments with conditi... |
"""
SOURCE:
https://stackoverflow.com/questions/5525782/adjust-label-positioning-in-axes3d-of-matplotlib
DESCRIPTION:
Creates and returns a figure using matplotlib
uses with a bunch of default settings that are logical,
and consistent with the physics community.
ARGS:
CheckArguments
Type:
... |
import numpy
"""
Computes the Euclidean distance between two n-vectors ``Point1`` and ``Point2``,
which is defined as
.. math::
{||Point1-Point2||}_2
Parameters
----------
Point1 : ndarray
An :math:`n`-dimensional vector.
Point2 : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
Th... |
"""
SOURCE:
Mind of Douglas Adams
https://realpython.com/python-rounding/
https://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python
DESCRIPTION:
Rounds a number.
This library is the home for the many
options which are available depending on the circumsta... |
"""
SOURCE:
Mind of Douglas Adams
DESCRIPTION:
Lazily dump an object to the local computer
ARGS:
CheckArguments
Type:
python boolean
Description:
if true, checks the arguments with conditions written in the function
if false, ignores those conditions
... |
# To be interactively typed in order to explore TF basics.
# Following Oriley's: Hello TensorFlow
## Basic Exploration ##
import tensorflow as tf
graph = tf.get_default_graph()
graph.get_operations()
input_value = tf.constant(1.0)
operations = graph.get_operations()
operations
operations[0].node_def
sess = tf.S... |
def termCount(search_term, search_text):
a = len(search_term)
b = len(search_text)
frequency = 0
for i in range(b - a + 1):
j = 0
while j < a:
if (search_text[i + j] != search_term[j]):
break
j += 1
if (j == a):
frequency += ... |
'''
Created on 30 nov. 2016
@author: usuario
'''
def crearLista(lista):
'''
voy a hacer una lista donde incluya una serie de elemenetos
'''
for indice in range(5):
try:
elemento=int(input("introducir un elemento"))
lista.append(elemento)
... |
#Author: Mohamed Abdelkader
from Core import Core
class Scanner:
# Constructor should open the file and find the first token
def __init__(self, filename):
#Create a dictionary of the keywords and specials in the Core file
self.keywords = {
"program":Core.PROGRAM,
"begin": Core.BEGIN,
"en... |
from turtle import Turtle
class Paddle(Turtle):
def __init__(self, position):
super().__init__(shape="square")
self.penup()
self.color("white")
self.shapesize(5, 1)
self.setposition(position)
def move(self, direction):
if direction == "up":
new_y =... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import random
import collections
import math
import sys
from collections import Counter
from util import *
############################################################
# Problem 2: binary classification
############################################################
##########... |
import TCPServer
import TCPClient
if __name__=="__main__":
slct=input("[+] Enter 1 for server 2 for client")
if slct=='1':
TCPServer.TCPServer.server_connect()
elif slct=='2':
TCPClient.client_connect()
else:
print("!!Wrong input, good bye !!")
exit()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, Michael Chigaev.
#
# F1bw is free software; you can redistribute it and/or modify
# it under the terms of the 3-Clause BSD License; see LICENSE.txt
# file for more details.
import sys
import click
@click.command()
@click.option("-f", is_flag=True... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: CC(zizou)
# Email: yyccbbz@l63.com
# pythonstudy--list_tuple
# 2017/5/16 14:39
import copy
names = ["Alex", "Tenglan", "Eric", "Rain", "Tom", "Amy"]
a = names[1:4] # 取下标1至下标4之间的数字,包括1,不包括4
print("a = ", a)
print(type(a))
b = names[1:-1] # 取下标1至-1的值,不包括-1
pri... |
num = input("Please input number: ")
check = input("Please input check number: ")
num = int(num)
check = int(check)
if num % 4 == 0:
print (num , " is a multiple of 4")
elif num % 2 == 0:
print (num, " is even number")
else:
print (num, "is odd number")
if num % check == 0:
print (num, "its evenly div... |
#4
base = int(input("Nhap base: "))
hight = int(input("Nhap hight: "))
print("Dien tich: ", 0.5 * base * hight)
#5
a = int(input("Nhap canh thu 1: "))
b = int(input("Nhap canh thu 2: "))
c = int(input("Nhap canh thu 3: "))
print("chu_vi: ", a + b + c)
#6
length = int(input("Nhap chieu dai: "))
width = int(input("N... |
/**
* http://www.lintcode.com/zh-cn/problem/binary-tree-inorder-traversal/#
*
*
*/
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: Inorder ... |
#Grocery List Price Calculator
import random
store_options = {"Bread": 2.99, "Turkey": 3.99, "Apple": 1.00, "Onion": 0.50,
"Olive Oil": 5.00, "Flank Steak": 12.00, "Salmon": 8.00,
"Bag of Pretzel": 1.99}
total = 0
for key in store_options:
num_of_items = random.randrange... |
def find_pair(values, desired_sum):
try:
values_set = {int(v) for v in sorted(values) if v > 0}
except Exception as e: # int() throws an error for anything that can't be cast as an integer
return None
if len(values_set) < len(values): # there were duplicates or a value less than 1
... |
# CS110A
# Homework 3
# 01-26-2020
# Program divides the number of riders by the number of days.
# Then, program outputs the resulting average daily ridership.
x = str(input("Welcome to the Muni Ridership Calculator. Which Muni line did you survey? "))
y = int(input("How many days did you survey? "))
z = int(inp... |
import re
def word_abbr(s, abbr):
"""Given a non-empty string s and an abbreviation abbr, return whether the string matches withthe given abbreviation."""
s_list = re.findall(r"(\d+|[a-z]+)", abbr)
pattern = ""
for i in s_list:
if i.isdigit():
pattern += int(i) * "[a-z]"
el... |
sort_list = [3, 5, 2, 1, 4]
for i in range(1, 5):
while i > 0 and sort_list[i] < sort_list[i-1]:
sort_list[i-1], sort_list[i] = sort_list[i], sort_list[i-1]
i -= 1
|
class Book:
def __init__(self,
title,
authors,
year,
ISBN,
pages,
publisher,
tags):
self.title = title
self.authors = authors
self.year = year
self.ISBN = ISBN
... |
"""
Given two strings, determine if one is an anagram of the other. For example, the two strings “anagram” and “margana” are anagrams of each other.
"""
def is_anagram(string_1: str, string_2: str) -> bool:
n = len(string_1)
if len(string_2) != n:
return False
for i in range(n):
if string_1... |
"""
Estimate the time complexity of merge sort for the best, reverse and worst cases.
filename: merge_timing.py
author: Jiawei Li
date: 20/9/2020
"""
import time
import pandas as pd
from random import sample
import altair as alt
def create_lists(n):
number_list = list(range(0, n))
reverse_list = list(range(n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 20 19:50:14 2021
@author: 蔡侑廷
"""
math = input('Please enter math grade ')
math = int(math)
eng = input('Please enter english grade ')
eng = int(eng)
if math >= 90 and eng >= 90:
print('YOU WIN A PRIZE ')
elif math == 100 or eng == 100:
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
def reverse(r):
if r.next is None:
return r
head = tail = r
cur = r.next
while cur:
tmp = cur.next
head.next = tmp
cur.next = t... |
import math
def binary_search(array, value):
searched_position = -1
current_pos = len(array) - 1
min_pos = 0
max_pos = len(array) - 1
n = 0
while True:
if array[current_pos] == value:
searched_position = current_pos
break
elif value > array[current_pos]:... |
class PriorityQueue:
def __init__(self, s):
self.heap = []
self.heap_size = 0
self.s = s
def insert(self, el):
self.heap.append(el)
self.heap_size += 1
i = self.heap_size - 1
p = (i - 1) // 2
while p >= 0 and self.s(self.heap[p], self.heap[i]):
... |
import sys
sys.path.append('libsvm/python/')
from svmutil import svm_train, svm_predict
'''
Homework5: support vector machine classifier
You need to use two functions 'svm_train' and 'svm_predict'
from libsvm library to start your homework. Please read the
readme.txt file carefully to understand how to use these
two... |
#Even or odd number
print ("This program shows if a number is even or odd and if a multiple of 4!")
a= int(input ("Please input a number: "))
mod= a%2
if mod==0:
print (str(a) + ' is Even')
else:
print(str(a) + 'is Odd')
if a%4==0:
print (str(a) + ' is a multiple of 4')
|
print ('Hello World')
str1 = input ('Plz enter your name\n')
dict1={}
for i in str1:
if i in dict1:
dict1[i]= dict1[i]+1
else:
dict1[i]=1
print(dict1)
|
# Assignment 3 Dictionaries
# A program that combines several dictionaries into a new dictionary with all the keys of the original dictionaries
"""If a key appears in more than one input dictionary, the value corresponding to that key in the new dictionary should
be a list containing all the values encountered in th... |
# establishes formatter variable, which can passed through to .format which will line up the following variables with the {}
formatter = "{} {} {} {}"
# prints text; passes through to format function to fill the brackets -{}- in variable
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "th... |
class Car:
def __init__(self,color, model):
self.color = color
self.model = model
self.engine = "off"
def start_engine(self):
if self.engine == "off":
print("Starting Engine!")
self.engine = "on"
else:
print("The engine is running already!")
def stop_engine(self):
if self.engine == "on":
... |
print("Enter a file name: ")
file_name = input()
myfile = open(file_name, "r+")
print("The file is ", len(myfile.read().splitlines()), "lines long")
|
import pandas as pd
import sqlite3
fish_df = pd.read_csv('./static/fish.csv', index_col=0)
bugs_df = pd.read_csv('./static/bugs.csv', index_col=0)
with sqlite3.connect("db.sqlite") as conn:
fish_df.to_sql("fish", con=conn, if_exists="replace", index=False)
bugs_df.to_sql("bugs", con=conn, if_exists="replace... |
#!/usr/bin/python
#
# TODO
# - command line
# - alternate left/right?
# - favor letters over symbols for extras
# - words
import random
import sys
import string
class PasswordPhrase:
def __init__(self, num_words=4, wordlen_min=4, wordlen_max=10, seed=37):
self.num_words = num_words
if wordlen_max ... |
# str
temp = 42
print "The temperature is " + `temp` # bad formation
print "The temperature is " + repr(temp) # repr is a function
print "The temperature is " + str(temp) # str is a type,
#same as int..
print '-' * 50
# long string
print '''This is a very long string.
It continues here.
And not yet over.
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.