text stringlengths 37 1.41M |
|---|
def main():
sequence = input("Enter RNA Sequence : ")
count = 0
sequence = clean_sequence(sequence)
if(len(sequence)<3):
print("ERROR : Sequence length is not sufficient to proceed.")
else:
sequences = find_sequences(sequence)
print(sequences)
for seq in sequences:
... |
"""create a simple CNN classification model with keras"""
from tensorflow import keras
def main():
(train_images, train_labels), (test_images, test_labels) = keras.datasets.mnist.load_data()
# improves accuracy ~89% to ~93%
train_images, test_images = train_images / 255.0, test_images / 255.0
model =... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/6/21 15:17
# @Author : zhe
# @FileName : CList.py
# @Project : PyCharm
from .node import LNode, DLNode, LinkedListUnderflow
# 循环单链表
class LCList:
def __init__(self):
self._rear = None
def is_empty(self):
return self._rear ... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/9 13:50
# @Author : zhe
# @FileName : simple_sorting_algorithm.py
# @Project : PyCharm
def insert_sort(lst):
'''
插入排序
:param lst: 待排序的list
:return: 这里直接修改待排序的list,不需要返回
'''
for i in range(1, len(lst)):
value = lst[i... |
"""
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
import time
day={'Monday':0,'Tuesday':1,'Wednesday':2,'Thursday':3,'Friday':4,'Saturday':5,'Sunday':6}
present_year_day=1
count=0
def count_sunday(year,day):
global count
for i in range(1,13):
... |
"""
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
"""
exponent=5
upper_bound=(exponent+1) * (9**exponent)
fifth_power=[] # list of all those no which stasify the property
for i in xrange(2,upper_bound):
num=str(i) #to make integer iterable
k=0 #sum of fifth powe... |
multiplicand = int(input(" enter multiplier here "))
print(" 17 * 1 = " , multiplicand*1)
print(" 17 * 2 = " , multiplicand*2)
print(" 17 * 3 = " , multiplicand*3)
print(" 17 * 4 = " , multiplicand*4)
print(" 17 * 5 = " , multiplicand*5)
print(" 17 * 6 = " , multiplicand*6)
print(" 17 * 7 = " , mult... |
# https://leetcode.com/problems/implement-queue-using-stacks
class MyQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, x: int) -> None:
self.stack1.append(x);
def pop(self) -> int:
if (len(self.stack2) > 0):
r... |
from collections import defaultdict
def parse_dictionary(dictionary_file: str = "") -> dict[int, str]:
word_length_to_words = defaultdict(list)
with open(dictionary_file) as f:
for line in f.readlines():
word = line.strip()
n = len(word)
word_length_to_words[n].appe... |
"""Program that outputs one of at least four random, good fortunes."""
__author__ = "730402712"
from random import randint
random_number: int = randint(1, 4)
print("Your fortune cookie says...")
if random_number < 2:
print("There is a great romance in you future, you are going to fall in love with a very powerf... |
# -*- coding: utf-8 -*-
from sklearn import preprocessing
import numpy as np
a = np.random.random((1, 4))
print(a)
a = a*20
print("Data = ", a)
# normalize the data attributes
normalized = preprocessing.normalize(a)
print("Normalized Data = ", normalized) |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
import math
from keras.models import load_model
# loading pre trained model
model = load_model('cnn_model/digit_classifier.h5')
# Reshaping to feed our image to the model and get prediction
def predict_digit(img):
test_image =... |
b_b = 3
print("b_b_b:{}".format(b_b))
def print_b_b():
print("print B_b:{}".format(b_b))
class ClassB:
B = 3
print("Class B init")
def __init__(self, *args, **kwargs):
self.name = "B class"
def print_name(self):
print("ClassB name:{}".format(self.name))
@classmethod
... |
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __lt__(self, other):
if self.grade != other.grade:
return self.grade < other.grade
return self.name < other.name
class School(object):
def __init__(self):
self._stude... |
def n_natural_numbers(number):
return range(1, number + 1)
def square_of_sum(number):
return sum(n_natural_numbers(number)) ** 2
def sum_of_squares(number):
return sum(map(lambda n: n ** 2, n_natural_numbers(number)))
def difference_of_squares(number):
return square_of_sum(number) - sum_of_squares(number) |
# Develop a program that calculates the distance between two cities
# and allows the user to specify a unit of distance. This program
# may require finding coordinates for the citias like latitude and longitude.
# ---------------- COMPLETED ----------------
import googlemaps
import math
def distance(lat1, lng1, lat... |
from time import time
def p41():
""" Pandigital prime
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, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
"""
import sys
... |
# Develop a program that has the user enter a number.
# Your program should print out the Fibonacci sequence to the Nth number.
# ---------------- COMPLETED ----------------
def fibonacci(number):
sequence = []
fibonacci_number = fibonacci_generator()
while len(sequence) < number:
sequence.append(... |
# Write some code that simulates flipping a single coin however many times the user decides.
# The code should record the outcomes and count the number of taisl and heads.
from random import random
def flip_coin():
return random() < 0.5
def print_stats(flips):
heads = len([_ for _ in flips if _])
print... |
# # Exercise (easy)
# Create a dict with your friends ages
#
# # Exercise (easy)
# Transform this dict:
# ```python
# {0: 10, 1: 20}
# ```
# into this:
# ```python
# {0: 10, 1: 20, 2: 30}
# ```
#
# # Exercise (easy)
# Write a Python program to get the maximum and minimum value in a dictionary.
#
# # Exercise (easy)
... |
# Lucky 7
# for loop
# Read an integer number n. This is a number of integer values you will receive on the next n lines.
# Among these numbers find the multiples of 7 (that is, numbers that could be divided by 7 without the remainder)
# and print their squares. Each square number should be printed on a new line.
num ... |
# A Topp
# Cat cafes, loop control statements
# Each string contains a café's name followed by a space and the number of cats in it, e.g. Paws 11, Kittens 9.
# The names would be one-word only. Read input lines until you get a string MEOW (without any number).
cafe_list = []
f_list = []
while True:
cafes = input... |
# Exercise Question 1: Given a string of odd length greater 7,
# return a string made of the middle three chars of a given String
def getmidthreechars(str1):
midindex = int(len(str1)/2)
print('Original string is', str1)
midstr = str1[midindex-1:midindex+2]
print('Chars in the middle are', midstr)
ge... |
'''
Utility functions for vectors.
'''
import math
def crossproduct3(a, b):
'''
:return: vector 3-D cross product of a and b
'''
return [ a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0] ]
def dotproduct(a, b):
'''
:return: vector dot (inner) product of a and b
'''
... |
from clear import clear
from helpModule import Help
from random import randint
riddles = [["What gets bigger, when you take from it?", "hole"], ["I travel the world, but never leave my corner, what am I?", "stamp"], ["I have holes but I can still hold water, what am I?", "sponge"]]
def riddle():
"""Riddle of the ... |
# FILE CONTAING THE ANT CLASS AND RELATED FUNCTIONS
import random as r
from ui import *
def add_Ants():#Everytime an ant finds food this is called to increase the size of the colony
global antSpawnCounter
antSpawnCounter += 1
if antSpawnCounter % antSpawnFreq == 0:
if antSpawnCounter % (antSpawnFr... |
import abc
import json
import numbers
import operator
from collections import OrderedDict
#abstract base class representing the configuration of a machine learning algorithm
class Configuration( abc.ABC ):
_required_parameters = set()
def __init__( self, **input_configuration ):
#parame... |
import math
import util
import random
import point
class STPoint(object):
def __init__(self, x, y, t):
self.x = x
self.y = y
self.t = t
def get_x(self):
return self.x
def get_y(self):
return self.y
def get_t(self):
return self.t
def within(self... |
class Solution(object):
def uniquePaths(self, m, n):
matrix = [[0 for i in range(m+1)] for j in range(n+1)]
matrix[1][0] = 1
for j in range(1, n+1):
for i in range(1, m+1):
matrix[j][i] = matrix[j-1][i] + matrix[j][i-1]
print(matrix)
return matri... |
class Solution(object):
def strStr(self, haystack, needle):
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
solution = Solution()
print(solution.strStr('hello', 'llo'))
print(solution.strStr('aaaaaa', 'bba'))
|
class Solution(object):
def maxSubArray(self, nums):
if len(nums) == 0:
return 0
curValue = maxValue = nums[0]
for value in nums[1:]:
curValue = max(value, value + curValue)
maxValue = max(curValue, maxValue)
return maxValue
def maxSubArray2(... |
'''
Instruction:
Prospective student data is organized in the superheroes.csv file such that the data for each
student is on one line, with the values separated by tabs. An example of two students’ data
might be:
Student,SAT,GPA,Interest,High School Quality,Sem1,Sem2,Sem3,Sem4
Abbess Horror ,1300,3.61,10,7,95,86,91,94
... |
# find the most common used words from a string (a paragraph)
import re
def findMostCommonWords (literatureText, wordsToExclude):
# replace all the punctuation letters with space
literatureText = re.sub(r"[,.;@#?!&$+*'\"]", " ", literatureText)
print "after re.sub literatureText is \n " + literatureTex... |
#Jessica Qinying Wu
#This is the Sudoku project
#Start: April 29, 2020
import random
import warnings
import math
import time
import numpy as np
from colorama import Fore
INDICES={1,2,3,4,5,6,7,8,9}
HINTS=3
INSTRUCTIONS='\nInput Command Instruction\n\n P:Place a number in a cell\n R: Remove a number from a cell\n H: R... |
import csv
from datetime import datetime
DEGREE_SYBMOL = u"\N{DEGREE SIGN}C"
def format_temperature(temp): #done
"""Takes a temperature and returns it in string format with the degrees
and celcius symbols.
Args:
temp: A string representing a temperature.
Returns:
A string contain... |
def startButton():
history = input("E escuta um barulho vindo da sala a esquerda, ele abre a porta, e la está um elevador vermelhor com um placa dizendo START GAME, você deseja entrar?")
if history.lower() in ["sim", "claro", "s"]:
print("JOGO DA VIDA OU MORTE")
print(" Você vai entrar e... |
import random
import matplotlib.pyplot as plt
x=[]
y=[]
#random.seed(555)
for i in range(0,10):
x.append(random.random())
#random.seed(555)
for i in range(0,10):
y.append(random.random())
plt.plot(x,y,'g*')
plt.xlabel('x')
plt.ylabel('y')
|
"""
Code for Tutorial on Parameter Estimation by Maximum Likelihood Fitting
Modified by Kathleen Eckert from an activity written by Sheila Kannappan
"""
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as npr
# Generating fake data set to start with:
alphatrue=2. # slope
betatrue=5. ... |
#Assignment 2
string = "It's thanksgiving day. It's my birthday,too!"
print string
print string.find("day")
string = string.replace("day", "month")
print string
#part 2
x = [-10,2,3,9,37]
print x
print min(x)
print max(x)
#part 3
x = ["Heya","Howdy","Howsitgoin",1,2,3]
print x[0], x[len(x) - 1]
#print4
x= [12,3,4,6,... |
def odd_even():
for x in range(1, 2001):
if x % 2 == 0:
print x, "This is an even number"
else:
print x, "This is an odd number"
odd_even()
def multiply(arr, num):
for x in range(0, len(arr)):
arr[x] *= num
return arr
num_array = [3, 6, 8, 10, 67]
print mul... |
def helper(xxs, n):
s = set()
def loop(xxs, n):
if len(xxs) == 0:
return False
x = xxs[0]
if x in s:
return True
else:
s.add(n - x)
return loop(xxs[1:], n)
return loop(xxs, n)
assert helper([10, 15, 3, 7], 17) == True
assert h... |
def contains(list_1, list_2):
a =0
while True:
if list_2 == list_1[a : a + len(list_2)]:
return True
break
else:
a += 1
if a + len(list_2) > len(list_1):
return False
break
list1 = [1, 6, 2, 1, 4, 1, 2, 1, 8]
list2 = [1, 2, 1]
print(contains(list1, list2))... |
# this program is useful in showing different ways you can use positional parameters
def birthday1(name, age):
""" No default values """
print("Happy birthday,", name, "!", " I hear you're", age, "today.\n")
def birthday2(name = "Jackson", age = 1):
""" Default values """
print("Happy birthday,", ... |
# you can open a text file and read it with python
# you can interact with it in many ways, including as a list
print("\nReading characters from the file.")
text_file = open("read_it.txt", "r")
print(text_file.read(1))
print(text_file.read(5))
lines = text_file.readlines()
for line in lines:
print (line)
te... |
# As we already know we have a few data types:
# float
# int
# str
# bool
# we also have data structures:
# list [] , these are ordered and indexed numerically
# tuple
# dictionary
# use help() to see the documentation of functions
# or put a ? in front
help(round)
# data types are objects and have inbuilt methods... |
temp = int(input("Enter first amount in Celsius: "))
lines = int(input("Enter the number of lines for the table: "))
diff = int(input("Enter a whole number difference between lines in Celsius: "))
fara = temp * 1.8 + 32
print("\tCELSIUS", "\tFARENHEIT")
print("")
while lines != 0:
print ("\t ", temp , "\t\t", ... |
import numpy as np
# numpy has lots of inbuilt mathematical functions such as mean and median
np_2d = np.array([[1.7, 1.6, 1.8, 2], [65, 59, 88, 93]])
print("Mean:", np.mean(np_2d[1]))
print("Median:", np.median(np_2d[0]))
# other common functions include correlation coefficient, np.corrcoef and standard deviation np... |
def loadpokedex():
global pokedex
text_file = open("Pokedex.csv", "r")
for line in text_file:
both = line.split(',')
num = int(both[0])
pokemon = both[1]
pokedex[num] = pokemon
def check():
global pokedex
global close
try:
num = int(input("What is your po... |
#Good morning! Here's your coding interview problem for today.
#
#This problem was asked by Google.
#
#Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
#
#For example, given the following Node... |
# Majority Element
'''
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.
Input -> Array Ints
Output -> Integer
Ex:
input -> majorityElement([2,2,1... |
a = input("Enter 1st number:")
b = input("Enter 2nd number:")
sum = int(a) + int(b)
print int(sum)
|
## import from all
from monsters_monster import *
from student_monster import *
from monster_course import *
print("Welcome to Monsters Inc. University! Ready to learn?")
#create two student objects
tytus = student_monster('Tytus', '223', 'blue', '0001', ['fast', 'strong'])
leandro = student_monster('Leandro', '11... |
#!/usr/bin/env python3
import math
class Int9:
"""
An integer over Z9 (module 9) field
"""
def __init__(self, n: int):
self.n = n % 9
def __add__(self, other):
return Int9(self.n + other.n)
def __sub__(self, other):
return Int9(self.n - other.n)
def __mul__(self... |
import unittest
from day12.modules.util import utility
class UtilityTest(unittest.TestCase):
def test_mult(self):
num1 = 2
num2 = 3
expected = 6
result = utility.mult(num1, num2)
self.assertEqual(expected, result)
def test_add(self):
result = utility.add(5, 8)
... |
from functools import reduce
def generator(n):
for el in range(1, n+1):
yield reduce(lambda x, y: x * y, [el1 for el1 in range(1, el + 1)])
i = 1
for numb in generator(int(input("Введите число, для которого надо вычислить факториал: "))):
print(f"{i}! = {numb}")
i += 1
|
from itertools import count, cycle
for el in count(3):
if el > 10:
break
else:
print(el)
list_repeat = ["cat", "dog"]
i = 1
for el in cycle(list_repeat):
if i > 10:
break
print(el)
i += 1 |
i = 1
while True:
print("Введите данные сотрудника. Если вы хотите прекратить ввод данных, введите вместо имени символ #.")
name_inp = input(f"Введите имя номер {i}: ")
if name_inp != "#":
surname_inp = input(f"Введите фамилию номер {i}: ")
year_inp = input(f"Введите год рождения номер {i}: ... |
class Car:
speed: int
colour: str
name: str
is_police: bool
def __init__(self, name, colour, speed, is_police=False):
self.name = name
self.colour = colour
self.speed = speed
self.is_police = is_police
def go(self):
print("Машина поехала")
def stop(... |
def my_func(var_1, var_2, var_3):
return sum((var_1, var_2, var_3)) - min((var_1, var_2, var_3))
"""Это вариант с введенными заранее числами"""
#print("Даны три числа: 10, 8, 5")
#print("Сумма наибольших двух составляет:", my_func(10, 8, 5)
"""Вариант когда числа вводит пользователь."""
var_1 = int(input("Введит... |
'''
Словарь, тип dict(dictionary). Тип данных существующий в виде пар ключ-значение
Синтаксис dict: dict = {'ключ': Значение, 'ключ': Значение }
Все ключи уникальны, повторений быть не может
Обновление и добавление осуществляется с помощью присвоения
dict[key]=new_data
Функция get выдает значение по ключу
Функция setd... |
#Declaring variables
a1="abc"
a2="def"
a3="ghi"
#Using find command
print "variable options \na1 \na2 \na3\n"
a00 = raw_input("enter the variable to search: ")
if a00 =="a1" or a00=="a2" or a00=="a3": #if anything else input script stops
a01 = raw_input("enter the string to find: ")
a11 = a00.find(a01)
... |
# Create list baseball
baseball = [180, 215, 210, 210, 188, 176, 209, 200]
# Import the numpy package as np
import numpy as np
# Create a numpy array from baseball: np_baseball
np_baseball = np.array(baseball)
# Print out type of np_baseball
print(type(np_baseball))
# height is available as a regular list
# Import... |
import numpy as np
def initialize_with_zeros(dim):
"""
This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.
Argument:
dim -- size of the w vector we want (or number of parameters in this case)
Returns:
w -- initialized vector of shape (dim, 1)
b ... |
#!/usr/bin/env python
# -*- coding: cp1254 -*-
#
# Test cases for tournament.py
from tournament import *
import math
from random import randint
def testDeleteMatches():
deleteMatches()
print "1. Old matches can be deleted."
def testDelete():
deleteMatches()
deletePlayers()
print... |
# words = ['alice', 'john', 'bob', 'alice', 'john', 'alice']
# maqsad = 'alice'
words = input("Vergul bilan ajaratib so'zlar kiriting: ").split(sep=",")
maqsad = input("Maqsad so'zni kiriting: ")
result = words.count(maqsad)
print(result) |
names = input("Ismlarni vergul bilan ajratib kiriting: ").split(",")
def ReverseList(names):
return names[::-1]
print(ReverseList(names)) |
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^\d+$"
test_str = "1"
cre = re.compile(regex)
matches = re.search(regex, test_str)
m2 = cre.search(test_str)
print(m2)
if matches:
print("Match was found at {start}-{end}: {match}".format(s... |
# a=int(input("enter the num="))
# b=a%10
# c=a//10
# d=c%10
# f=c//10
# e=f%10
# g=f//10
# print(b,d,e)
a=6
b=6
if a>6:
print("a equal to b")
else:
print("manvi")
|
# Showing how weakrefs work (as used in Element-parent relations.
# Arbitrary object
a = [123,342,34,324,234]
# Make two indepdent references. This does not copy a into b and c.
b = a
c = a
# Make a refer to another object.
a = 123
# Check that b still refers to the content of a, although a lost reference to it.
# Thi... |
def main():
matrix = [[0 for j in range(5)] for i in range(5)]
row, col = 0, 0
for i in range(5):
for j in range(5):
matrix[i][j] = int(input())
if matrix[i][j] == 1:
row = i+1
col = j+1
pos = 0
if 3-row < 0:
row = (-1*(3-row))... |
def main():
t = int(input())
ans = []
while t:
a = int(input())
b = int(input())
c = int(input())
d = int(input())
temp = [b, c, c]
ans.append(temp)
t -= 1
for i in ans:
for j in i:
print(j, end=" ")
print()
if __name_... |
import turtle
import sys
pen = turtle.Turtle()
#draw a circle
def circle(size, color):
pen.fillcolor(color)
pen.begin_fill()
pen.circle(size)
pen.end_fill()
# drawing a triangle
def triangle(size, color):
pen.fillcolor(color)
pen.begin_fill()
x = 0
while x < 3:
pen.forward(size)
pen.right(120)
x += 1
... |
import random
import time
import datetime
def opening_csv_file(filecsv="countries_and_capitals.txt"):
'''convert csv file to list of couples country | capital'''
Countryfile = open(filecsv) # OTWIERANIE PLIKU
text_country_capital = Countryfile.read() # CZYTA... |
#type(Returns the class/datatype of passed value)
integer = 10
double = 10.0
string = "Random String"
print(type(integer))
print(type(double))
print(type(string)) |
def checkSubstring(substring, givenString):
return substring in givenString.lower()
TrueString = 'This contains substring'
FalseString = 'This do not contain'
TrueResult = checkSubstring('substring',TrueString)
FalseResult = checkSubstring('substrign',FalseString)
print(TrueResult) #Prints True
print(False... |
for integer in range(1,100):
if(integer%3==0):
print("fizz")
continue
if(integer%5)
print(integer) |
from database import Database
from models.blog import Blog
from models.post import Post
class Menu(object):
def __init__(self):
self.user = input("Author name? ")
self.user_blog = None
if self._user_exists():
print("Welcome back {}".format(self.user))
else:
... |
# first_name = "Joe"
# last_name = "Lee"
# sentence = "My name is {} {}".format(first_name, last_name)
# print(sentence)
# sentence = f"My name is {first_name.upper()} {last_name.upper()}"
# print(sentence)
# person = {"name": "Jenn", "age": 23}
# sentence = "My name is {} and I am {} years old".format(person["name... |
# Decorators - functions that takes another function as an argument, adds some type of
# functionality and returns another function. All of this without altering the source code
# of the original function that you passed in.
from functools import wraps # used when chaining decorators
def decorator_function(original_... |
# -*- coding: utf-8 -*-
# # 06 list and tuple
# list is a sortable collection
workmates = ['ZhangSan', 'LiSi', 'WangWu']
print(workmates)
print(len(workmates))
print(workmates[0], workmates[1], workmates[2])
print(workmates[-1], workmates[-2], workmates[-3])
# add elements
workmates.append('Steve')
print(workmates)
wo... |
x = int(input())
y = int(input())
z = int(input())
if x <= y and x <= z:
print (x)
if y <= x and y <= z:
print (y)
if z <= y and z <= x:
print (z)
|
"""
This module defines the Race class
"""
from typing import TYPE_CHECKING, Any, Dict, List
from uctl2_back.race_state import RaceStatus
from uctl2_back.team import Team
if TYPE_CHECKING:
from uctl2_back.stage import Stage
from uctl2_back.uctl2_setup import PointsWithDistance
class Race:
"""
... |
# Generate prime numbers
import datetime, sys, math
# Function to print message
def print_prime(x):
print " Prime : %7i " %x
# Function to search for prime numbers
# within number range
def find_primes(upper_limit):
count = 0
candidate = 3
while(candidate <= upper_limit):
trial_divisor = 2
prime = ... |
import numpy as np
import matplotlib.pyplot as plt
from utils.plot import plot_line_graph
def set_initials(pos_0, vel_0, t_array):
"""common to verlet and euler programs"""
#initiliase arrays
dims = len(pos_0)
N = len(t_array)
pos_array = np.empty(shape=(N, dims))
vel_array = np.emp... |
"""Utilities for extracting probabilities and measures from counts dict"""
import logging
import math
class WordFrequency(object):
def __init__(self, frequency_model):
self.d = frequency_model
def count(self, verb, noun):
"""Returns count from dict, given a verb and a noun"""
try:
... |
#1
import simplegui
# Draw handler
def draw(canvas):
canvas.draw_text("It works!",[120, 112], 48, "Red")
# Create frame and assign callbacks to event handlers
frame = simplegui.create_frame("It works", 400, 200)
frame.set_draw_handler(draw)
frame.start()
#2
import simplegui
# Draw handler
def draw(canvas... |
'''
Created on 20 Oct 2013
@author: Antonio
'''
import unittest
from SelectionSort import selectionSort
from InsertionSort import insertionSort
class Test(unittest.TestCase):
def testSort(self):
testSorted = [1, 3, 5, 6]
test1 = [1 ,3, 5, 6]
self.assertEqual(selectionSort(test1)... |
# -*- encoding: tilde -*-
'''
exp ~ (1, some_var, (2,3), 'hello')
is the same as exp == (1, some_var, (2,3), 'hello')
exp ~ (1, ...)
three dots at the end - any number of lasst parameters
exp ~ (int, _, (2, _), 'hello')
int|str|list|tuple -> matches only things of that type
... |
"""
LSTM example
Code from tutorial: https://www.knowledgemapper.com/knowmap/knowbook/jasdeepchhabra94@gmail.comUnderstandingLSTMinTensorflow(MNISTdataset)
"""
import tensorflow as tf
from tensorflow.contrib import rnn
# Import mnist dataset
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_d... |
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""A tiny Python program to check that Python is working.
Try running this program from t... |
from collections import deque
# Get all the middle elements of a tuple
def drop_first_last(data):
first, *middle, last = data
return middle
# A cool recursive algorithm
def cool_sum(lst):
head, *tail = lst
return head + sum(tail) if tail else head
# Return the matching line with he previous line bef... |
import itertools
file_characters = open("pc_02.txt", "rt")
characters = file_characters.read()
file_characters.close()
secret_word = ""
for l in characters:
count = str.count(characters, l)
if count == 1:
secret_word += l
print(secret_word) |
class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
self.books = {}
self.user_books = {}
self.more_book =[]
self.books_prices = {}
def get_email(self):
return self.email
def change_email(self, address):
se... |
class lingkaran(object):
def __init__(self, p, r):
self.phi = p
self.jarijari = r
def hitungkeliling(self):
return 2* self.phi * self.jarijari
def hitungluas(self):
return self.phi * self.jarijari * self.jarijari
def main():
#Keliling Lingkaran
lingkaransatu = lingkara... |
"""
This script is the central script to run for taking new data GPX files and adding them to the database. Documentation
for it can be found in the Puerto Rico Google Drive under the 2018-2019 --> Subteams --> Design folder
"""
# import libraries
from database.gpxfuncs import loadgpx, loadgpxfiles
from old.databaseFu... |
# -*- coding: utf-8 -*-
import simple_draw as sd
# Запросить у пользователя желаемую фигуру посредством выбора из существующих
# вывести список всех фигур с номерами и ждать ввода номера желаемой фигуры.
# и нарисовать эту фигуру в центре экрана
# Код функций из упр lesson_004/02_global_color.py скопировать сюда
#... |
"""
Input and output functions to store, parse and export Spotify data.
"""
import datetime
from typing import Any, Dict, Iterable, Optional
from tabulate import tabulate
DATE_FORMAT = "%Y-%m-%d"
def parse_artists(
artists_json: Iterable[Dict[str, Any]], print_date: bool = True
) -> str:
"""Parses artists ... |
def ispalindrome(num):
if(reverse(num)==num):
return 1
def reverse(num):
rev=0
while(num>0):
rem=num%10
num=int(num/10)
rev=10*rev+rem
return rev
num=int(input())
coun=0
if(ispalindrome(num)==1):
print (num)
else:
while(1):
... |
done_number_array = [2, 1, 37, 5, 3, 24, 1, 3, 36, 1, 2, 13, 3, 5, 26, 9, 2, 24, 8, 49, 9]
x, y, z = [int(x) for x in input("Please enter 3 keys (separted by space): ").split()]
print("The key",x,"is found",done_number_array.count(x), " times in the database")
print("The key",y,"is found",done_number_array.count... |
def dele(nums,val):
if not nums :
return 0
nums[:] = [i for i in nums if i!=val]
return len(nums)
nums = [2,2,3]
len = dele(nums,2)
print(nums)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.