text stringlengths 37 1.41M |
|---|
"""
Explain why an attribute is never really private in Python. In your
explanation, please explain the process of name mangling with an example.
An attribute is not really private in Python; because we can access both
public and non-public attributes.
Name mangling is triggered when an attribute name is prec... |
import numpy as np
def u(points):
"""
Potential function.
"""
potential = 0
# The potential is the sum of all the forces between each pair of molecules.
for j in range(3, len(points), 3):
for i in range(0, j, 3):
r = ((points[i] - points[j])**2 + (points[i + 1] - points[j +... |
def frage_passwort():
""" Das Passwort Abfrage programm, verbessert als Funktion"""
SECRET_PASSWORD = "passwort1"
triesLeft = 3
correctPassword = False
while triesLeft > 0 and not correctPassword:
user_input = input("Geben Sie hier ihr Passwort ein:\n")
if(user_input == SECRET_PASS... |
from math import inf
# eigene Funktion impotieren
from test import frage_passwort
def square_number(number):
"""f(x) = x^2 (x hoch 2)"""
return number * number
# Aufgabe 2a.2
def get_smallest_number(numbers):
"""a)"""
smallest_number = inf
for number in numbers:
if number < smallest_num... |
# Hier sollen wieder alle Kombinationen von 1 bis zu einer bestimmten Zahl
# paarweise multipliziert werden. Hier soll jedoch die Obergrenze vom User
# abgefragt werden.
correct_input = False
while not correct_input:
try:
user_number = int(input("Gib eine positive Zahl ein.\n"))
except ValueError:
... |
#code showing how to read a file and title it
import pandas as pd
movies = pd.read_csv ('C:/Users/Modupe/Desktop/gitgirl/movies_metadata.csv', index_col = None)
named_movie = movies.set_index('title')
named_movie = movies.loc ['Grumpier Old Men']
print ('Data for movie titled - Grumpier Old Men:\n')
named_movie
#sort... |
# Colby Darrah
# 3/23/2021
# 7-20. line graph pg 405
# using matplotlib to graph a line.
# change the name of "matplotlib.pylot" to "plt" for ease of re-writing
# create alias for matplotlib.pyplot
import matplotlib.pyplot as plt
def main():
# Create lists with the X and Y coordinates of each data point... |
# Colby Darrah
# 3/23/2021
# spotlight 7-08 example pg 385
# program calculates the total of a list.
# NUM_EMPLOYEES is used as a constant for the size of the list.
NUM_EMPLOYEES = 6
def main():
# Create a list.
numbers = [2, 4, 6, 8, 10]
# Create a variable to use as an accumulator.
tot... |
# 6-15 ....1 of 4 programs used by coffee company to manage
# inventory.
# This program adds coffee inventory records to the coffee.txt file.
def main()
# Create a variable to control the loop
another = 'y'
# Open the coffee.txt file in append mode.
coffee_file = open('coffee.txt',... |
# Colby Darrah
# 3/23/2021
# spotlight pg 440
# this code uses operator 'in' and 'not in' to determine if one strong
# contains another string
def main():
# EXAMPLE ----- IF-ELSE **IN** to check if string contains smaller string
text = 'Four score and seven years ago'
if 'seven' in text:
prin... |
# Colby Darrah
# 3/23/2021
# SPOTLIGHT pg 448
# VALIDATING THE CHARACTERS IN A PASSWORD
#password must be at least 7 characters long, have 1 upper case, 1 lower case,
# and 1 number
# program must accept password as argument and validate it meets criteria.
# **********program uses earlier spotlight code to get... |
# Colby Darrah
# 3/23/2021
# 8.1.1 pg 434
# use index [ ] to get specific character in the string.
def main():
# EXAMPLE 1 ------------------------------------------------------------
# create variable with string.
my_string = 'Roses are red'
# assign the character in the 6th position (sale starti... |
# Colby Darrah
# 3/23/2021
# 8.2 pg 439
# slicing strings, w step value, neg step value
def main():
# EXAMPLE 1 ------------------------------------------------------------
#this is the format:
# string[start_slice_index : end_slice_index]
full_name = 'Patty Lynn Smith'
middle_name = full_nam... |
# 6-30 pg 352 TRY / EXCEPT / ELSE
# ELSE suite (statement after Else Clause) executes after statements in the TRY
# suite, but only if no exceptions were raised. If an exception is raised, the
# ELSE suite is skipped.
# This program uses one exception clause to catch all exceptions raised in
# in the try sui... |
# Colby Darrah
# 3/23/2021
# COPY a list method pg 383
# demonstrates how to copy a list to have 2, separate, but identical lists.
def main():
# Create a list.
list_1 = [1, 2, 3, 4, 5]
#=====================FIRST METHOD TO COPY LIST (LESS ELEQUENT)===============
# Create an empty list
list... |
# Colby Darrah
# 3/23/2021
# pg 506
# Serialized Objects
# 1. pickling object pg 506
# 2. unpickling object pg 507
# * serializing an object it is converted to a stream of bytes that can be easily stored
# in a file for later retrieval.
# * sets, dictionaries, lists, tuples, strings... |
"""
Used to store and manage information related to an airline ticket agent.
"""
class TicketAgent:
"""
Creates a ticket agent object.
"""
def __init__( self, idNum ):
self._idNum = idNum
self._passenger = None
self._stopTime = -1
def idNum( self ):
"""
Gets... |
import random
def replace_unnecessary_symbols(word_to_modify):
temp_word = word_to_modify.lower()
temp_word = temp_word.replace('.', '')
temp_word = temp_word.replace(',', '')
temp_word = temp_word.replace('"', '')
temp_word = temp_word.replace("'", '')
temp_word = temp_word.replace('... |
# 一维数组
print([i * 2 for i in range(10)])
print([i * i for i in range(10)])
print([i * i for i in range(10) if (i % 3) == 0])
print([(x, y) for x in range(3) for y in range(3)])
print('')
# 二维数组
a = [[3] * (i + 1) for i in range(3)]
print(a[2])
print('')
# 乘法的问题
a = [[1, 2, 3]] * 3
a[1][1] = 100
print(a... |
class MyClass:
def __init__(self, val):
self.val = val
def display(self, s):
print('%s: %d' % (s, self.val))
m = MyClass(100)
print(m.val)
m.display('hello')
print('')
m2 = m
print(id(m))
print(id(m2))
fn = m.display
fn('hey')
|
#https://www.hackerrank.com/challenges/word-order/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import OrderedDict
n = int(raw_input())
d = OrderedDict()
for i in range(n):
line = raw_input()
d[line] = d[line] + 1 if line in d else 1
print len(d)
s = ""
for ... |
from datetime import datetime, date, timedelta
import calendar
import os
class Diary(object):
@staticmethod
def valid_month(month_str):
try:
return datetime.strptime(month_str, '%Y-%m')
except ValueError:
return None
@staticmethod
def valid_year(year_str):
... |
name = input("Wie heisst Du? ")
if (name == "Alexander"):
print ("Hallo, " + name)
else:
print ("Sicher nicht!")
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 20 20:10:45 2020
@author: Robert
"""
# ---------- RESOURCES --------------
# https://machinelearningmastery.com/how-to-configure-image-data-augmentation-when-training-deep-learning-neural-networks/
# https://machinelearningmastery.com/image-augmentation-deep-learn... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
def report(wages):
students = wages.keys()
students.sort()
for student in students:
print ('%-20s %12.2f' % (student, wages[student]))
wages = {'Mary': 6.23, 'Joe': 4.25, 'Joshua Red Man': 4.25}
report(wages) |
#!/usr/bin/python
#-*-coding: latin1-*-
from cards import Deck
from hand import Hand
class CardGame:
def __init__(self):
self.deck = Deck()
self.deck.shuffle()
class OldMaidHand(Hand):
def removeMatches(self):
count = 0
originalCards = self.cards[:]
for card in orig... |
'''
r'^A\\[(.*)\\]$'
#此句中 r 表示去掉反斜杠的转移机制
'''
import re
line = "a[book1,test5,1005, book6,test6,1006, book7,test7,1007, book8,test8,1008]"
s = '^A\\[(.*)\\]$'
pattern = re.compile(s, re.I)
match = re.match(pattern, line)
if match :
print(match.group(1))
pattern = "^A\\[(.*)\\]$"
match = re.match(pattern, line, re... |
def func(*args):
result = 0
for i in args:
try:
result+=i
except TypeError:
continue
return result
a=func(1,2,3,5)
print(a)
def func_2(*args):
result=0
numbers=float(input("1:"))
for i in numbers:
try:
result+=i
except TypeErr... |
#####################################################################
# Name: Dawson Markham
# Date: 3/24/2019
# Program: Vigenere Cipher
# Descritption: Program ecncrypts or decrypts user input using a
# vigenere cipher with a user specified key. Encryption/
# Decryption mode set by user in the f... |
# 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
#
# 说明:
#
# 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
#
# 示例 1:
#
# 输入: [2,2,1]
# 输出: 1
# 示例 2:
#
# 输入: [4,1,2,1,2]
# 输出: 4
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/single-number
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from typing import List
class Solution:
... |
# 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
#
# push(x) —— 将元素 x 推入栈中。
# pop() —— 删除栈顶的元素。
# top() —— 获取栈顶元素。
# getMin() —— 检索栈中的最小元素。
#
#
# 示例:
#
# 输入:
# ["MinStack","push","push","push","getMin","pop","top","getMin"]
# [[],[-2],[0],[-3],[],[],[],[]]
#
# 输出:
# [null,null,null,null,-3,null,0,-2]
#
# 解释:
# MinStack ... |
# 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
#
# 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
#
# 示例:
#
# 给定 nums = [2, 7, 11, 15], target = 9
#
# 因为 nums[0] + nums[1] = 2 + 7 = 9
# 所以返回 [0, 1]
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/two-sum
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solut... |
# 给定一个二叉树,检查它是否是镜像对称的。
#
#
#
# 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
#
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
#
#
# 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
#
# 1
# / \
# 2 2
# \ \
# 3 3
#
#
# 进阶:
#
# 你可以运用递归和迭代两种方法解决这个问题吗?
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/symmetric-... |
# 给定一个二叉树,判断它是否是高度平衡的二叉树。
#
# 本题中,一棵高度平衡二叉树定义为:
#
# 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
#
# 示例 1:
#
# 给定二叉树 [3,9,20,null,null,15,7]
#
# 3
# / \
# 9 20
# / \
# 15 7
# 返回 true 。
#
# 示例 2:
#
# 给定二叉树 [1,2,2,3,3,null,null,4,4]
#
# 1
# / \
# 2 2
# / \
# 3 3
# / \
# 4 4
# 返回 fa... |
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
finally:
if conn:
... |
'''
April 25, 2019
Using a function rand7() that returns an integer from 1 to 7 (inclusive) with
uniform probability, implement a function rand5() that returns an integer
from 1 to 5 (inclusive).
'''
import numpy as np
def rand7():
return np.random.randint(low=1, high=8)
def rand5():
while True:
x =... |
'''
June 14, 2019
Given a string which we can delete at most k, return whether you can make a
palindrome.
For example, given 'waterrfetawx' and a k of 2, you could delete f and x to
get 'waterretaw'.
'''
def k_deletions_to_palindrome(string, k=0):
def _recurse(string, k):
if string == string[::-1]:
... |
'''
May 3, 2019
Given an array of integers, write a function to determine whether the array
could become non-decreasing by modifying at most 1 element.
For example, given the array [10, 5, 7], you should return true, since we can
modify the 10 into a 1 to make the array non-decreasing.
Given the array [10, 5, 1], yo... |
'''
March 12, 2019
Given a string of round, curly, and square open and closing brackets, return
whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
'''
OPENER = 1
CLOSER = -1
def validate_str... |
'''
May 1, 2019
Given a list of possibly overlapping intervals, return a new list of intervals
where all overlapping intervals have been merged.
The input list is not necessarily ordered in any way.
For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should return
[(1, 3), (4, 10), (20, 25)].
'''
# So it's ... |
'''
June 2, 2019
Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd
bit should be swapped, the 3rd and 4th bit should be swapped, and so on.
For example, 10101010 should be 01010101. 11100010 should be 11010001.
Bonus: Can you do this in one line?
'''
'''
Explanation: (so that I understand... |
'''
May 14, 2019
Given an integer n and a list of integers l, write a function that randomly
generates a number from 0 to n-1 that isn't in l (uniform).
'''
import numpy as np
def random_number_not_in_l(n, l):
return np.random.choice(list(set(range(n)) - set(l)))
if __name__ == '__main__':
import sys
n ... |
'''
May 4, 2019
Given the root of a binary tree, return a deepest node. For example, in the
following tree, return d.
a
/ \
b c
/
d
'''
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# Yes, it also re... |
'''
April 19, 2019
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
You should print out the following:
1
2
3
4
5
10
15
20
... |
'''
March 11, 2019
Given a singly linked list and an integer k, remove the kth last element from
the list. k is guaranteed to be smaller than the length of the list.
The list is very long, so making more than one pass is prohibitively expensive.
Do this in constant space and in one pass.
'''
class SinglyLinkedList:... |
'''
May 29, 2019
Given a function f, and N return a debounced f of N milliseconds.
That is, as long as the debounced f continues to be invoked, f itself will not
be called for N milliseconds.
'''
from datetime import datetime, timedelta
def debounce(N):
def debounce_decorator(func):
run_time = datetime.... |
'''
March 7, 2019
Given a dictionary of words and a string made up of those words (no spaces),
return the original sentence in a list. If there is more than one possible
reconstruction, return any of them. If there is no possible reconstruction,
then return null.
For example, given the set of words 'quick', 'brown', ... |
'''RGB to HEX converter'''
def rgb_hex():
invalid_msg = "ERROR!!Invalid values"
red=int(raw_input("Enter red Value(0-255) :"))
if(red not in range(0,256)):
print invalid_msg
return
green=int(raw_input("Enter green Value(0-255 :"))
if(green not in range(0,256)):
print invalid_msg
return
blue=... |
#!/usr/bin/python
import random
from utils.log import log
"""
BasicBot
This basic bot will play the next card in its hard every turn
All competing bots should extend this model
"""
class BasicBot:
def __init__(self, player_num, num_players, num_cards, num_games):
#Bot is initialized once at the beginning of the com... |
import sqlite3
conn=sqlite3.connect("Ages.sqlite")
cur=conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS Ages(name VARCHAR(128), age INTEGER)''')
cur.execute('''DELETE FROM Ages''');
cur.execute('''INSERT INTO Ages (name, age) VALUES ("Marta", 25)''');
cur.execute('''INSERT INTO Ages (name, age) VALUES ('Rhuai... |
def area_of_a_triangle(x, y, z):
s = 1 / 2 * (x + y + z)
area = (s) * (s - x) * (s - y) * (s - z)
area = area ** 0.5
return area
print(area_of_a_triangle(3, 4, 5))
|
# -*- coding: utf-8 -*-
''' Simple interpreter for visiting ast.
Referenced implementations:
Interpreter for Pascal written in Python:
https://github.com/rspivak/lsbasi/blob/master/part17/spi.py
Interpreter.interpret is the main program.
'''
from .tokenizer import Operator
class Interpreter:
def __i... |
import numpy
import matplotlib.pyplot as plot
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
data = pd.read_csv('C:\python\property.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, 1].values
linearRegressor = LinearRegression()... |
def total(initial=5, *numbers, **keywords):
count=initial
print count
print numbers
print keywords
print '---------1-------------'
for number in numbers:
print ' #### 1-1 ####'
print number
count += number
print 'count is : ', count
print '---------2-------------'
for key in keywords:
print key
c... |
import random
class CoolTree:
def __init__(self, x, y, value = None):
self.x = x
self.y = y
self.value = value
self.left = None
self.right = None
def insert(self, child):
if self.value > child.value:
if self.left == None:
self.lef... |
def main():
pinCode = ["1234", "1999", "2424", "1985", "5555"] #data of the account holders
accountHoldersName = ["harry den", "zain ul abideen", "waseema shaukat", "ayesha mukhtar", "khalid mahmood"]
accountNumber = ['1353', '199281', "182838", "185597", "667432"]
balance = [567000, 21873, 2341871, 275... |
import time
def cpu_bound(number):
return sum(i * i for i in range(number))
def find_sums(numbers):
for number in numbers:
cpu_bound(number)
if __name__=='__main__':
numbers = [5_000_000 + x for x in range(20)]
start_time = time.time()
find_sums(numbers)
duration = time.time() - start_time
print(f'Duration... |
'''
Created on Jan 23, 2017
@author: dsbrown
'''
import numpy as np
from solvers import mdp
import math
#TODO figure out terminal and None action with end of game
class MountainCarGridMDP(mdp.MDP):
"""A two-dimensional grid MDP, as in [Figure 17.1]. All you have to do is
specify the grid as a list of list... |
"""
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and fini... |
"""
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... |
def printBoard(board):
print(' | | ')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | | ')
print('------------')
print(' | | ')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | | ')
print('------------')
print(' | ... |
if __name__ == '__main__':
str1 = 'I Like Python'
str2 = str1
print(str1,str2)
str2 = 'I Like PHP'
print(str1, str2)
str3 = 'I Like PHP'
print(id(str2), id(str3))
"""
由于PHP与Python表达变量的意义不一样,所以PHP的可变变量在Python中是不存在的
Python的任何类型都是对象,变量只是对象的一个引用,如上面str2一开始是与str1一样指向'I Li... |
# modified from official documentation
# -*- coding=utf-8 -*-
# !/usr/bin/env python
import multiprocessing
import queue
def f(n, a):
n.value = 3.14
# 普通类型判断用type,类对象的类型判断用isinstance方法
if type(a) == type(multiprocessing.Array("i", range(10))) and len(a) > 0:
a[0] = 5
def modify(q):
if type... |
#This uses urlopen to access a site, then uses BeautifulSoup to get the
#HTML from that site, and then cuts out all of the non-text
import re
from bs4 import BeautifulSoup
import requests
class Professor:
person = ""
quality = ""
takeAgain = ""
difficulty = ""
def __init__(self, name):
self... |
n = int(input())
for i in range(1, n+1):
spaces = n - i
for j in range(spaces):
print(' ',end = '')
for j in range(i):
print(j+1,end = '')
print() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
from Bio import SeqIO
def get_args():
Description = 'RNA fasta to DNA fasta'
parser = argparse.ArgumentParser(description=Description)
parser.add_argument(
'input',
help='Input file',
)
args = parser.parse_args()
r... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 16 11:56:53 2017
@author: warrenl0134
"""
dayofweek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday','Sunday']
for i in range(1,6,2):
print(dayofweek[i]) |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 8 11:52:33 2017
@author: warrenl0134
"""
def three_letters(string):
return(string[0:3] * 3)
print(three_letters("patriots")) |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 12 11:15:45 2018
@author: warrenl0134
"""
#derivative calc
#prompts user for values in the equation
print("all equations are in ax^2 + bx + c form")
power1 = int(input("enter a power factor: "))
a = int(input("enter the a value: "))
b = int(input("enter the... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 27 11:34:42 2017
@author: warrenl0134
"""
# defines a function that ensures that a str input can be a int
def get_num (string):
try:
int(string)
return True
except:
return False
# fulfills all the requirements under a false con... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 28 11:40:50 2017
@author: warrenl0134
"""
#Multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products' digits together.
#Add the sum to the sum of the digits that weren’t multiplied by 2.
#If the total’s last di... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 12:00:10 2017
@author: warrenl0134
"""
x = 0
end = int(input("enter a number: "))
while x <= end:
x += x
x += 1
print(x) |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 20:13:15 2017
@author: warrenl0134
"""
def max1020(a,b):
if (a or b) >= 10 and (a or b) <= 20:
if a > b:
return a
else:
return b
else:
return 0
print(max1020(10,20))
|
## regular expressions ###
import re
def match_sxz(noun):
return re.search('[sxz]$',noun)
def apply_sxz(noun):
return re.sub('$','es',noun)
def match_h(noun):
return re.search('[^aeioudgkprt]h$',noun)
def apply_h(noun):
return re.sub('$','es',noun)
def match_y(noun):
return re.search('[^aeiou]y$',noun)
... |
def read_grades(gradefile):
''' (file open for reading) -> list of float
Read and return the list of grades in gradefile.
Precondition: gradefilestarts with a header that
contains no blank lines, then has a blank line,
and then lines containing a student number and
a grade.
'''
... |
a = int(input()) # яблоки
n = int(input()) # школоло
print('Каждому школьнику по',a // n, 'яблок')
print('В корзине осталось',a % n, 'яблок')
|
import bisect
BISECT_UNFIND_RET = -1
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return BISECT_UNFIND_RET
# Usage:
if __name__ == "__main__":
arr = [1,3,5]
print index(arr, 2)
print index(arr, 3... |
"""
This module implements a multi-layer perceptron in NumPy.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
class MLP(object):
"""
This class implements a Multi-layer Perceptron in NumPy.
It handles the different layers and pa... |
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence... |
# Imports to be used
import csv
import sys
from util import Node, nodeQueue
# objects to be used for mapping
names = {} # will corespond to person_ids
people = {} # will correspond to a dict of: name, dob, set of movie ids
movies = {} # will correspond to a dict of: title, year, starts (set of person ids)
# load... |
"""
User Geo Location
=================
Get Geo location of user using https://ipstack.com/
written by: vimmrana0@gmail.com (vimm0)
original repository: https://github.com/vimm0/auto-script
USAGE:
=====
- Generate Free API key from https://ipstack.com/
- Obtain your ip address
- run the code
"""
import os
import reque... |
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# You can return the answer in any order.
# Example 1:
# Input: nums = [2,7,11,15], ... |
from cryptography.fernet import Fernet
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw()
#file = open('key.key', 'rb')
f = askopenfilename() #otvaram file gdje je key za enkripciju
file = open(f, "rb")
key = file.read() # The key will be type bytes
file.close()
enc_fil... |
class Person:
"""
This is a person class
"""
staticDefaultClass='NA'
def __init__(self, name,age):
self.name = name
self.age=age
def talk(self):
print(f"talking {self.name}")
def __str__(self):
return f"{self.name}"
def __len__(self):
return sel... |
name=input('esmetan ra vared konid')
family=input('familetan ra vared konid')
avarage1=int(input('nomre1:'))
avarage2=int(input('nomre2:'))
avarage3=int(input('nomre3:'))
moadel=(avarage1+avarage2+avarage3)/3
if moadel>=17:
print('great')
elif moadel<17 and moadel==12 and moadel>12 :
print('normal')
e... |
import numpy as np
def linearRegCostFunction(X, y, theta, Lambda):
"""computes the
cost of using theta as the parameter for linear regression to fit the
data points in X and y. Returns the cost in J and the gradient in grad
"""
# Initialize some useful values
m = y.size # number of training example... |
#Pruebas 1
b = 0
a = int(input("Seleccione: "))
print(" ")
while a == 1:
b+=1
c = hex(b)
print(c)
if b == 20:
print("\nrompiendo...\n")
break
print("---------------------------------------------------------------")
print(f"Hola el numero que ingreso es {a} y el ... |
graph = {
'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E']),
'G': set([])
}
# 4.2 Simple DFS
def routeExists(graph, start, end):
if _routeExists(graph, start, end) == None... |
def even(n):
if n==1:
return 2
return even(n-1) + 2
print(even(20)) |
import csv # used for reading csv files
# Setting global variables
i = 0 # to iterate a 2D array for students
k = 0 # to iterate a 2D array for supervisors
y = 1 # to properly save student preference to the student array
pref = []
pref_supervisor = []
student = []
supervisor = []
area = []
# Setting streams reads an... |
from functools import reduce
input_file = 'input.txt'
def process_input():
with open(input_file) as f:
content = f.readlines()
grid = [x.strip() for x in content]
return grid
def bin_mult(c):
# useful tool that converts B/R to 1
if c == 'B' or c == 'R':
return 1
return 0
def get_row(str):
#... |
import pygame
from pygame.draw import *
peach = 245, 175, 127
black = 0, 0, 0
white = 255, 255, 255
green = 44, 105, 56
red = 255, 0, 0
pi = 3.14
pygame.init()
FPS = 30
sc = pygame.display.set_mode((1024, 640))
sc.fill(peach)
def leaf(x, y, w, h, angle): # this draws one leaf
surf = pygame.Surface((int(3 * w),... |
from tkinter import *
author = 'Jencent Dizon'
link = "https://github.com/I-am-Programmer-101"
print("Author:",author,"\nLink:",link)
MyRootDialog=Tk()
#Set Tkinter Size And Location
MyRootDialog.geometry("400x400")
#Set Tkinter Title
MyRootDialog.title("Information")
rt = Toplevel()
rt.title("Informa... |
#i = 0
#numbers = []
def myfun(a,b):
i = 0
numbers = []
while i < a:
print(f"At the top i is {i}")
numbers.append(i)
i += b
print("Numbers now ", numbers)
print(f"At the bottom i is {i}")
#a = int(input("Enter a number"))
myfun(int(input("Enter a num... |
#it imports argv function from the module sys
from sys import argv
#unpacks the argv in script and tx15
#it means you have to give two arguments while running the script
script, tx15 =argv
#open function with parameter tx15 , opens the file and keeps it in variable txt
txt = open(tx15)
print(f"Here is your... |
days = "Mon Tue Wed Thu Fri Sat Sun"
Months = "Jan \n Feb \n March \nApril\n June\nJuly\nAug\nSept\nOct\nNov\nDec"
print("Here are the days", days)
print("Here are the months", Months)
#It is multiline print statement , which uses triple quotes
print("""
This is the first time im using triple time double quot... |
c=int(input("Enter the temperature in celcius:"))
f=(c*9/5)+32
print(f"Temperature in farenheit is: {f}")
|
print('Введите скорость транспортного средства в км/ч?')
a = int(input())
print('Введите время движения транспортного средства')
b = int(input())
print('Час ', 'Пройденное расстояние' )
c = 1
while c != b+1:
print(c,' ', (c*a))
c += 1;
|
# Quiz Creation Activity
import time
from rich import print
# Quiz has five questions the user will answer.
# It will keep track of score and give
# a final result
a = float(input(f"1 + 1 = "))
score = 0
if a == 2:
print(f"You're right")
score = score + 1
else:
print(f"You're wrong")
b = input(f"Potter ... |
#!/usr/bin/env python3
"""takes the DNA sequences as an input from a single external file
and saves the best alignment along with its corresponding score
in a single text file (your choice of format and file type) to an appropriate location. """
__author__ = 'Yuchen YANG (YY5819@ic.ac.uk)'
__version__ = '0.0.1'
# T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.