text stringlengths 37 1.41M |
|---|
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
def insert_after(self, value):
pass
def insert_before(self, value):
pass
def delete(self):
pass
class DoublyLinkedList:
def __init__(self):
self.head = None
... |
# Name : Yogi Halagunaki
# Assignment No : 3(Que 3)
# Questions 3:
# Write a code snippet to find the dimensions of a ndarray and its size.
import numpy as np
my_array_one = np.array([[1, 4, 7], [3, 6, 9], [1, 4, 7], [3, 6, 9]])
print("calculating Dimensions of a nd array is :", my_array_one.ndim)
print("Size of an... |
def is_member(letter, word):
'''
arg -> letter, word
return -> returns True if the word has the letter
else False
'''
for char in word:
if char == letter:
return True
return False
letter = 'a'
word = 'Test'
print('Check whether the word', word, 'has',
lett... |
class Event(object):
def __init__(self, sim, time):
self.sim = sim
self.time = time
def execute(self):
print('This method should be over-ridden!')
def __lt__(self, other):
return self.time < other.time
def __repr__(self):
return f'Event ({self.time})'
class Pr... |
import torch
from torch import nn
def gradient_descent(x, y):
w = 1.0
def forward(x):
y = x * w
return y
def cost(xs, ys):
# loss = 1/N * sum(y-y)**2
cost = 0
for x, y in zip(xs, ys):
pred = forward(x)
cost += (y - pred) ** 2
return ... |
import pandas as pd
import langdetect
def country(textstring):
lang=langdetect.detect(textstring)
print(lang)
return lang
df = pd.read_csv("amazon_review_full_csv/test.csv")
df["Detected Language"] = df["review"].apply(country)
df.to_csv("articles_lang.csv", index=False)
print(df.to_string()) |
"""
(c) January 2016 by Daniel Seita
This will run ridge regression using python's sklearn library.
"""
import numpy as np
from sklearn import linear_model
def do_regression(data, alpha=0.1):
"""
Perform regression using ridge regression, and *returns* the predictions.
:alpha: The parameter used to det... |
import sys
def main(argv):
if len(argv) != 1:
sys.exit('No valido')
list_prime=[]
d=2
n=int(sys.argv[1])
print "D: " +str(d)
while d*d <= n:
if (n % d) == 0:
list_prime.append(d)
n //= d
d=d+1
if n > 1:
list_prime.append(n)
for i in list_prime:
print "Primo: " +str(i)
if __name__ == "__ma... |
#!/usr/bin/python
import numpy
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tup... |
'''
requires PIL for image transformation
'''
import os
from PIL import Image
from tkinter import filedialog
def tiff_to_jpeg(calidad=75):
'''
Allows you to choose a folder in order to transform tiff images within the folder into new jpeg files
(creates a new file that shares name with initial t... |
# QuickSort using median-of-median (group 5) as a pivot.
# Input: Array which contains elements from Input.txt file
# Output: Sorted array written in output.txt file
import os, sys
import copy
import datetime
def median_quick(q, n):
sublist = []
median = []
pivot = None
if len(q) >= 1:
for i ... |
a=input()
count=0
for k in range(0,len(a)):
if(a[k]=='0' or a[k]=='1'):
count+=1
if count==len(a):
print("yes")
else:print("no")
|
'''
Para correr el archivo, usar este comando
python -m unittest unit_tests.py
Desarrolla y/o documenta una implementación apropiada para las siguientes clases: STACK (lifo), QUEUE (fifo),
TABLE/HASH/Hash (order),.. (* las puedes implementar “desde 0” o usar alguna librería “pública” *)
Las clases deben contener mét... |
#! /usr/bin/python3
from sys import argv
# python 2.x
#IP = raw_input('Enter IP address in format 10.10.10.10/24: ')
#python 3.x
#IP = input('Enter IP address in format 10.10.10.10/24: ')
IP = argv[1]
IP_b =[]
mask = IP.split("/")[1]
mask_d=[]
IP = IP.split("/")[0].split(".")
for i in range(0, len(IP)) :
IP[i]= ... |
class Solution(object):
def searchInsert(self, nums, target):
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r)/2
if nums[mid] == target:
return mid
elif target < nums[mid]:
if mid > 0 and target > nums[mid - 1]:
... |
from Util import ListNode
class Solution(object):
def swapPairs(self, head):
if head is None or head.next is None:
return head
second = head.next
head.next = self.swapPairs(second.next)
second.next = head
return second
a = ListNode(1)
b = ListNode(3)
c = List... |
from Util import ListNode
class Solution():
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1
if l1.val < l2.val:
head = l1
l1 = l1.next
else:
head = l2
l2 = l2.next
c... |
txt = 'but soft by yonder window breaks'
words = txt.split()
print (txt)
print (words)
t = list()
for word in words :
t.append((len(word),word))
print(t)
t.sort(reverse=True)
print(t)
res = list()
for length, word in t :
res.append(word)
print(res) |
m = []
while True:
n = input('enter a phrase: ')
if n == 'done' : break
m.append(n)
print (m)
crazy = m.split(';')
print (crazy) |
"""
Solution of Counting Sundays
https://www.hackerrank.com/contests/projecteuler/challenges/euler019
"""
def is_leap_year(year):
""" retunrs if 'year' is a leap year """
return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
def days_before_beginning_of_year(year):
""" returns days count between 1... |
class Inventory():
"""docstring for Inventory."""
def __init__(self, d=None):
if not d:
self.coin = {'cp': 0, 'sp': 0, 'ep': 0, 'gp': 0, 'pp': 0}
self.weapon = {'spife': 'It\'s a spoon-knife imbued with flavor from the inside of the last person\'s mouth who owned it.'}
... |
# importing relevant libraries
import os # For operative system commands
import random # For random number generator
# user chooses number of decks of cards to use
decks = input("Enter number of decks to use: ")
# possible amount of decks
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*(int(decks)*4)
# initia... |
from collections import OrderedDict, defaultdict
def topo_reader(file):
'''
read topology file from DCell format, convert to ordered dictionary
file: str, path to topology file
return OrderedDict, keys = [term]['GENES'] or [term]['TERMS'], in topological order (root at last)
'''
topo = OrderedDi... |
from random import randint
GAME_RULE = 'Find the greatest common divisor of given numbers.'
MAX_NUM = 100
def gcd(n1, n2):
while n2:
n1, n2 = n2, n1 % n2
return n1
def round():
num1 = randint(0, MAX_NUM)
num2 = randint(0, MAX_NUM)
correct_answer = str(gcd(num1, num2))
question = '... |
import asyncio
async def print_number():
for i in range(1,11):
print(i)
await asyncio.sleep(1)
async def fetch_data():
print("Start fetching")
await asyncio.sleep(2)
data = {"student_id":1, "student_name": "Patrick"}
print("Done fetching")
return data
async def main():
... |
for item in range(1, 20001):
if item % 2 != 0:
print "Number is", item, "This is an odd number."
else:
print "Number is", item, "This is an even number." |
persons = ["Anna","Kevin","Amy","Robert"]
age = ['101','102','103','104']
country =['United States', 'Canada', 'Mexico', 'Russia']
language =['Python','Java','Javascript']
# print persons
# print "My age is "+ age[0]
# print "My country of birth is The "+ country[0]
# print "My favorite language is "+ language[0]
# p... |
#Code for domain retrieval of entered url
from urllib.parse import urlsplit
url = input ('Enter url: ')
base_url = "{0.scheme}://{0.netloc}/".format(urlsplit(url))
print(base_url)
|
'''
Author: Matthew Mettler
Project Euler, Problem 23
https://projecteuler.net/problem=23
A perfect number is a number for which the sum of its proper divisors is
exactly equal to the number. For example, the sum of the proper divisors
of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect
number.
A... |
'''
Author: Matthew Mettler
Project Euler, Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of
all the multiples of 3 or 5 below 1000.
Status: Correct
'''
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 =... |
'''
Author: Matthew Mettler
Project Euler, Problem 5
2520 is the smallest number that can be divided by each of the numbers from 1
to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the
numbers from 1 to 20?
Status: Correct
'''
low = 1
high = 20
# Don't need to ch... |
from matplotlib import pyplot as plt
import collections
mentions = [500,505]
years = [2013, 2014]
plt.bar([2012.6, 2013.6], mentions, 0.8)
plt.xticks(years)
plt.ylabel("# of times I heard someone say 'data science'")
# if you don't do this, matplotlib will label the x-axis 0, 1
# and then add a +2.013e3 off in the c... |
from matplotlib import pyplot as plt
movies = ["Saw 1", "Spiderman", "Ironman", "Alicia en el pais de las maravillas", "Gandhi"]
numberOfOscars = [2,4,6,3,2]
# bars are by default width 0.8, so we'll add 0.1 to the left coordinates so that each bar is centered
xs = [i + 0.1 for i, _ in enumerate(movies)]
# plot bar... |
def selection_sort(arr):
for i in range(len(arr)):
smallest_index = i
for j in range(i+1, len(arr)):
if arr[smallest_index] > arr[j]:
smallest_index = j
arr[smallest_index], arr[i] = arr[i], arr[smallest_index]
return arr
|
import matplotlib.pyplot as plt
import csv
def convert_date(date):
""" Takes a date 'YYYYMMDD' and converts it to 'YYYY/MM/DD' """
date = [date[0:4], date[4:6], date[6:8]] # Split in year, month, day respectively
return "/".join(date)
def read_data(year, plot=False):
""" Write the temperature data ... |
# Bounce effect
# The bounce() function creates a bounce effect and accepts the r, g and b parameters to set the color, and the waiting time.
# The waiting time determines how fast the bouncing effect is.
from machine import Pin
from neopixel import NeoPixel
import time
from all.functions import clear
# clear
clear(3... |
# -*- coding: utf-8 -*-
"""
UnitTest for Millipede
"""
import unittest
import millipede
class TestMillipedeSize(unittest.TestCase):
"Test size parameter on millipede function"
def test_negative(self):
"Test with negative integer value"
self.assertEqual(
millipede.millipede(-1),
... |
import itertools
# FA. For all
# EQ. Equivalence <->
################################################################################
# Extensionality
# FA. u(U in X <-> U in Y) <-> X = Y
################################################################################
X = set(range(1, 5)) # {1, 2, 3, 4)
Y = {1, 2, 3, ... |
n=int(input("enter the number"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrom!")
else:
print("the number is not a palindrom!")
|
# Copyright 2012 Google Inc. All Rights Reserved.
"""Module representation.
A module is a simple namespace of rules, serving no purpose other than to allow
for easier organization of projects.
Rules may refer to other rules in the same module with a shorthand (':foo') or
rules in other modules by specifying a module... |
#!/usr/bin/python3
# Problem Statement #1 {{{
"""
In this assignment you will implement one or more algorithms for the all-pairs shortest-path problem.
Here are data files describing three graphs: g1.txt g2.txt g3.txt
The first line indicates the number of vertices and edges, respectively. Each subsequent line
descr... |
#!/usr/bin/python3
# Problem Statement #1 {{{
"""
In this programming problem you'll code up the dynamic programming algorithm
for computing a maximum-weight independent set of a path graph.
Download the text file below (mwis.txt).
This file describes the weights of the vertices in a path graph
(with the weights li... |
import random
print("Welcome to Nanda's Number Guessing game")
number = random.randint(1,9)
chances = 0
print("Guess a number(between 1-9):")
while chances < 5:
guess=="answermode":
guess=int(input("Enter your guess:-"))
if guess == number:
print("CONGRATULATIONS YOU WON!")
... |
# Given an object/dictionary with keys and values that consist of both strings and integers, design
# an algorithm to calculate and return the sum of all of the numeric values.
# For example, given the following object/dictionary as input:
data = {
"cat": "bob",
"dog": 23,
19: 18,
90: "fish"
}
# Your al... |
import random
options = ['rock','paper','scissor']
user_sc , comp_sc = int(0),int(0)
while (user_sc != 5 or comp_sc != 5):
comp_ch = random.choice(options)
user_ch = input(str('Enter your choice: rock,paper or scissor ')).lower()
if(user_ch == 'rock'):
if(comp_ch == 'scissor'):
print(... |
"""
You should write all of your functions in this file. That way we can
use parts of this file later in the course.
"""
# this line imports numpy as np, csv, os, etc.
from util import *
################################ Constants ####################################
# degree -> salaries
# college -> salaries
# Note tha... |
'''
This exercise is designed to get you familiar with
reading python's extensive documentation.
time's documentation link: https://docs.python.org/3/library/time.html
'''
import time
'''
Exercise 1:
Write a function that prints out the current time in military time.
Input: nothing
Returns: nothing
'''
# define and w... |
from typing import List
# Given an array of size n, find the majority element.
# The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# You may assume that the array is non-empty and the majority element
# always exist in the array.
class Solution:
def majorityElement(self, nums: List[int]) ->... |
import math
class Solution:
def reverse(self, x: int) -> int:
sign = 1 if x >= 0 else -1
x = abs(x)
rev = 0
while( x > 0 ):
dig = x % 10
rev = rev * 10 + dig
x = x // 10
if(rev > 0 and math.ceil(math.log(rev, 2)) > 31):
return 0... |
#We will be making a code to calculate the total amount of purchase
#04/03/2019
#CTI-110 P2HW2 - Meal Tip Calculator
#Richard T Buffalo
#
#Get their input with the chargeTotal variable.
chargeTotal = float(input('Enter the amount of meal: '))
#Tie in the variables tip and amount and do your calculations.
... |
# LIFO Stack
# Initialise variables
instruction = ""
stack = []
while instruction != "exit":
instruction = str(input("Pick an operation: push, pop, or view (or type exit): ")).strip()
if instruction == "push":
item = str(input("Enter the value to push on to the stack: ")).strip()
stack.app... |
'''
A combination is a selection of all or part of a set of objects,
without regard to the order in which objects are selected.
Each possible selection would be an example of a combination.
derivation:
n(P)r = permutation
n(P)r = c(r(P)r)
c = n(P)r / r(P)r
c = n!/(n-r)!r! = combination
c = (n r)'
'''
"""
Example... |
#AUTHOR: Manish NArwal
#PROFESSOR: Dr.Carlo Lipizzi
#ASSIGNMENT: Mid-term
#SECTION 2: CODE CHECKING
#PROBLEM #6
#Issues with Code:
#1)If you run it straight away then it is printing output as list
#2)And even output is not proper because L is multiplied by 3 at end of program
#Reason:
#1)Mutliplied ... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Shoblin
#
# Created: 02.01.2020
# Copyright: (c) Shoblin 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
import li... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: atopolskiy
#
# Created: 07.01.2021
# Copyright: (c) atopolskiy 2021
# Licence: <your licence>
#-------------------------------------------------------------------------------
de... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: atopolskiy
#
# Created: 07.12.2019
# Copyright: (c) atopolskiy 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
imp... |
valid = False
cont = True
counter = 1
while (valid == False):
userI = int(input("Enter how many users will be using the program: "))
run = userI
if (run < 1):
print("Invalid input! Input must be greater then 0!")
valid = False
else:
valid = True
while (counter ... |
def square(num):
return num**2
nums = [1, 2, 3, 4, 5]
# print(list(map(square, nums)))
# Lambda
print(list(map(lambda num: num ** 2, nums)))
def check_even(num):
return num % 2 == 0
even = list(filter(check_even, nums))
# print(even)
|
import math
class Line():
def __init__(self, coor1, coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
x1,y1 = self.coor1
x2,y2 = self.coor2
p1 = (x2 - x1) ** 2
p2 = (y2 - y1) ** 2
return (p1 + p2) ** 0.5
def slope(self):
x1,y... |
##############################################
# The MIT License (MIT)
# Copyright (c) 2016 Kevin Walchko
# see LICENSE for full details
##############################################
class Servo(object):
"""
Servo hold the parameters of a servo, it doesn't talk to real servos. This
class does the convers... |
def control_car(num):
if(num==1):
PressKey(W)
time.sleep(1)
ReleaseKey(W)
print("직진")
elif(num==2):
PressKey(A)
PressKey(W)
time.sleep(1)
ReleaseKey(A)
PressKey(W)
time.sleep(1)
ReleaseKey(W)
print("좌회전")
... |
#!/usr/bin/env python
from random import randint, sample, uniform
from acme import Product
import random as rand
# Useful to use with random.sample to generate names
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
Products = ... |
# create code w/following requirements
# 1. Variable 'confused' should be present in 3 scopes
# 2. Use 'global' or 'nonlocal' keyword
import sys
import string
import random
from colorama import init
init()
from colorama import Fore, Back, Style
confusion = "confused"
_global = "nonlocal"
_local = ""
class Scramble:... |
"""
Email BOT
----------------------------------------
This is my simple email bot that interact with you with voice and listen to you.
!! Note !!
if you want to use this bot you need give permission to from your google account.
you need to import SpeechRecognition, PyAudio, pyttsx3
"""
import smtplib
import speech_... |
'''
#二回ループを回していて効率が悪い
#文が無駄に長くなっているので、変数に代入して整理する
#出力が指定の通りになっていれば問題ないらしい
n = int(input())
num_list = list()
for num in range(n):
num_list.append(int(input()))
for num in range(n-1):
if num_list[num + 1] == num_list[num]:
print('stay')
elif num_list[num + 1] < num_list[num]:
print('down[{0... |
'''
Created on 22/10/2013
@author: CARLOS1
'''
#Write the Conversion of Celcius Grade to Farenheit Grade
#Read Temperature en Celsius
NCelcius = int(raw_input("Enter Celsius Grade (C): "))
#Convert to Farenheit
NFarenheit = NCelcius*1.8 + 32
#Write Farenheit Temperature
print "Farenheit Grade(F): " + str (N... |
# -*- coding: utf-8 -*-
import numpy as np
#a = np.arange(1,10)
a = np.array([1,3,5,7,9,11])
a = a.reshape(2,3)
print(a)
print(a.dtype)
print(a.ndim)
b = np.array([[1,3],[5,7],[9,11]])
print(b)
print(b.ndim)
|
"""
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example,
the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it i... |
"""
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once;
for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product
is 1 through 9 pandigital.
Fin... |
"""
70 colored balls are placed in an urn, 10 for each of the seven rainbow colors.
What is the expected number of distinct colors in 20 randomly picked balls?
Give your answer with nine digits after the decimal point (a.bcdefghij).
"""
import time
start_time = time.time()
"""
WORK
Expected value of pick 1 is 1
E... |
# import turtle
import turtle
# defining colors
colors = ['red', 'yellow', 'green', 'purple', 'blue', 'orange']
# setup turtle pen
t= turtle.Pen()
# changes the speed of the turtle
t.speed(10)
# changes the background color
turtle.bgcolor("black")
# make spiral_web
for x in range(200):
t.pencolor(colors[x%6]) # s... |
bursttime=[]
print("Enter number of process: ")
n=int(input())
processes=[]
for (i=0; i=n; i++)
processes.insert(i,i+1)
print("Enter the burst time of the processes: ")
for i in range(0,len(bursttime)-1):
for j in range(0,len(bursttime)-i-1):
if(bursttime[j]>bursttime[j+1]):
temp=bursttime[j]
bursttime[j]=b... |
def main(array):
quickSort(0,len(array)-1,array)
def quickSort(start, end, array):
if start < end :
p = partition(start, end, array)
quickSort(start, p-1, array)
quickSort(p+1, end, array)
def partition(start, end, array):
# taking start element as a pivot
pivotIndex = start
... |
def findstr(str,pattern):
tmp=str.find(pattern)
str2=str[0:tmp] + str[(tmp+len(pattern)):]
print(str2)
str=input("Enter a string: ")
pattern=input("Input a Pattern: ")
findstr(str,pattern) |
def allConstruct(targetString,wordBank):
if targetString == 0 : return []
a = []
for word in wordBank:
if targetString.find(word) == 0 :
suffix = targetString[len(word):]
result = allConstruct(suffix,wordBank)
a += result
return a
print(allConstruct("purple... |
def binarySearch(arr, left, right, key):
if right >= left:
mid = left + (right - left) // 2
if arr[mid] == key:
return mid
if arr[mid] > key :
return binarySearch(arr, left, mid-1, key)
else:
return binarySearch(arr, mid+1, right... |
def memo(func):
memory={}
def inner(num):
if num not in memory:
memory[num]=func(num)
return memory[num]
return inner
@memo
def facto(n):
if n==1:
return 1
else:
return n*facto(n-1)
print(facto(20)) |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 8 15:08:14 2020
@author: gulbarin
Student Name: Gülbarin Maçin
ID: 69163
"""
import random
#this method create random list which is a original list
def random_list():
n=random.randint(3,21)
randomlist = []
for i in range(n):
elt = ran... |
def getFarthestDistanceBetweenVertices( positions ):
if len(positions) <= 1:
return 0
edgeList = []
# add all edges and their cost to the list
while positions:
state = positions[0]
del positions[0]
# add all the edges from leading from the current state to all the other... |
# self and static method
class User:
username = ""
password = ""
def __init__(self, username="admin", password="1234"):
self.username = username
self.password = password
@staticmethod # บอกว่า function นี้เป็น static method
def test():
print("5678")
User.test() # เรียกตร... |
import helper
import rsa_encryption as rsa
import factoring as factor
import time
import sympy
def countTime(func, t):
start = time.time()
p, q = func(t)
print (p, q)
end = time.time()
return end - start
def readFile(file="pq.txt"):
f = open(file, "r")
for line in f:
p, q = line.s... |
# -*- coding: UTF-8 -*-
def merge(seq1, seq2):
seq = []
h = j = 0
while h < len(seq1) and j < len(seq2):
if seq1[h] < seq2[j]:
seq.append(seq1[h])
h = h+1
else:
seq.append(seq2[j])
j = j+1
if h == len(seq1):
for i in seq2[j:]:
... |
# -*- coding: UTF-8 -*-
def insertion_sort(seq):
for i in range(1, len(seq)):
key = seq[i]
j = i - 1
while j >= 0:
if seq[j] > key:
seq[j+1] = seq[j]
seq[j] = key
j = j -1
return seq
if __name__ == '__main__':
seq = [12, 3, 56,... |
"""Parse data from AmazonTestData.csv into a list of asin values
Assumptions:
-product information in csv file is accurate ie. corresponding ASIN matches correctly with title/product
"""
import csv
my_file = "/Users/Thoshi64/bottle/AmazonTestData.csv" #testing
def parse(raw_file, delimiter):
"""parses csv file... |
import matplotlib.pyplot as plt
import matplotlib
# from matplotlib import mpl
import numpy as np
# import matplotlib.animation as animation
import random
import math
def loadMap():
dataset="map.json"
import json
dataFile = open(dataset)
s = dataFile.read()
data = json.loads(s)
dataFile.close()... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 1 19:53:02 2019
@author: Mohammad Shahin
"""
class Text(object):
def __init__(self,text='',font=''):
self.text=text
self.font=font
def addText(self,text):
self.text=self.text+text
def getText(self):
return self.text
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 20:00:25 2019
@author: Mohammad Shahin
"""
def interlaced(st1,st2):
print(len(st2))
small=''
if len(st1)>len(st2):
x=st1[len(st2):]
small=st2[:]
elif len(st2)>len(st1):
x=st2[len(st1):]
small=st1[:]
res=''
for i i... |
import torch
# sigmoid activation function using pytorch
def sigmoid_activation(z):
return 1 / (1 + torch.exp(-z))
# function to calculate the derivative of activation
def sigmoid_delta(x):
return x * (1 - x)
n_input, n_hidden, n_output = 5,3,1
x = torch.randn((1, n_input))
y = torch.rand((1, n_output))
#... |
'''
Plotting libray, using Tkinter for expEYES
Author : Ajith Kumar B.P, bpajith@gmail.com
License : GNU GPL version 3
'''
import gettext, sys
gettext.bindtextdomain("expeyes")
gettext.textdomain('expeyes')
_ = gettext.gettext
VER = sys.version[0]
if VER == '3':
from tkinter import *
else:
from Tkinter import *
... |
# Write a procedure, speed_fraction, which takes as its inputs the result of
# a traceroute (in ms) and distance (in km) between two points. It should
# return the speed the data travels as a decimal fraction of the speed of
# light.
speed_of_light = 300000. # km per second
def speed_fraction(trace_time, distance):
... |
filename = input('input a filename:')
f_exten = filename.split('.')
print('The extension of the file is:' + repr(f_exten[-1])) # repr()将对象转化为string格式,输出的字符带有引号.
|
import random
import time
whoBats="NONE";
print("Welcome to Hand-cricket game!!")
print("RULES ****IF ANY PLAYER ENTER GREATER THAN 6,BATSMAN WILL GET OUT****")
print("1.Heads 2.Tails")
print("Choose Your option")
toss=int(input())
while(toss!=None):
if(toss>2):
print("Invalid option")
break
tos... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/6/1 下午12:26
# @Author : ziyi
# @File : time_test.py
# @Software: PyCharm
# import time
# import datetime
#
# # d = datetime.datetime.now()
# # print(d.month, d.day, d.time())
# nowtime = datetime.datetime.now()
# print(str(nowtime .time()).split(':'))... |
#三元运算符
# data = input("请输入:")
# val = int(data) if data.isdecimal() else None
word = "ase123qweasdw234eqas324dwqe213asd12"
temp=""
nums=[]
index = 0
while (index != len(word)):
target = word[index:index+1]
if (target.isdigit()):
temp += target
if (index == len(word) - 1):
nums.appen... |
a = input("Tast inn et heltall! ")
b = int(a)
if b < 10:
print(b + "Hei!") #Dette går ikke. Man kan ikke addere et heltall og en string.
#1. Dette er ikke lovlig kode. Man kan ikke addere et heltall og en string.
#2. Når vi kjører denne koden kommer vi til å få en feilmelding om linje 4.
|
#!/usr/bin/env python
#coding: utf-8
def feb(n):
if n < 1:
print("输入错误!")
return 1
n1 = 1
n2 = 1
n3 = 1
while (n-2) > 0:
n3 = n1 + n2
n1 = n2
n2 = n3
n -= 1
return n3
number = int(input("请输入一个正整数:"))
feb1 = feb(number)
print(feb1)
|
#-*- coding: utf-8 -*-
def fib(max):
n, a, b = 0, 0, 1
while n < max:
#print(b)
yield b ### print(b)改为yield b,函数就变成了一个生成器;
a, b = b,a + b
n = n + 1
return 'done'
fib(10)
|
print("Welcome to shop calculator")
DISCOUNT = 0.9
num = int(input("Please enter the number of item: "))
while num <= 0:
print("You have entered an invalid number")
num = int(input("Please enter the number of item: "))
total = 0.0
for i in range (0, num):
price = float(input("Please enter price of the item:... |
""" Programming II colour code """
COLOUR = {"AliceBlue": "#f0f8ff", "AntiqueWhite": "#faebd7", "AntiqueWhite1": " #ffefdb", "AntiqueWhite2": "#eedfcc",
"AntiqueWhite3": "#cdc0b0", "AntiqueWhite4": "#8b8378", "aquamarine1": "#7fffd4", "aquamarine2": "#76eec6",
"aquamarine4": "#458b740", "azure1": "... |
from prac_06.programming_language import ProgrammingLanguage
def main():
ruby = ProgrammingLanguage("Ruby", "Dynamic", True, 1995)
python = ProgrammingLanguage("Python", "Dynamic", True, 1991)
visual_basic = ProgrammingLanguage("Visual Basic", "Static", False, 1991)
print(ruby)
print(python)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.