text stringlengths 37 1.41M |
|---|
import numpy as np
from matplotlib import pyplot as plt
def lnFunc(x, n):
value = 0
term = 0
sign = 1
power = 1
while n > 0:
term = sign * (x ** power) / power
value = value + term
sign = - 1 * sign
power = power + 1
n = n - 1
... |
from node import Node
class BinaryTree:
def __init__(self, root_node: Node) -> None:
self.root = root_node
def __insert(self, node: Node, current_node: Node) -> str:
if node.data > current_node.data:
if current_node.right == None:
current_node.right = node
... |
class TreeNode:
def __init__(self, elem=-1, left=None, right=None):
self.elem = elem
self.left = left
self.right = right
class Tree:
"""数类"""
def __init__(self):
self.root = TreeNode()
def add(self, elem):
"""加入节点"""
node = TreeNode(elem)
if s... |
def MaxSum(array, n):
"""
连续子数组的最大乘积
动态规划 Max=Max{a[i],Max[i-1]*a[i],Min[i-1]*a[i]}Min=Min
创建一维数组
:param array:
:param n:
:return:
"""
maxA = [0 for i in range(n)]
minA = [0 for i in range(n)]
maxA[0] = array[0]
minA[0] = array[0]
value = maxA[0]
for i in range... |
# Скрипт. Задача-игра, Юзер угадывает число
import random
def game_user():
print('Компьютер загадал число от 1 до 100, попробуйте отгадать')
random_number = random.randint(1, 100)
user_answer = None
while user_answer != random_number:
user_answer = int(input('Введите число: '))
if use... |
# Запрос числа у пользователя
number = int(input('Enter number'))
# Прибавление к этому числу числа 2 в квадрате
result = number + 2**2
# Вывод результата на экран
print(result) |
# пример использования универсальной функции
# в которую в качестве одного из параметров передаем другую функцию
def my_filter (numbers, function):
result = []
for number in numbers:
if function (number):
result.append(number)
return result
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# передаем... |
# A empresa tinha um software para calcular a folha de ponto de TI
# A aplicação ficou tão boa que o diretor solicitou a mudança para que a mesma aplicação
# funcione para os varios setores e filiais da empresa
# Aplique o padrão composite visando calcular a folha de ponto da empresa
class Funcionario:
def __init__(s... |
import numpy
import random
def largest_number_in_both_lists(a, b):
for t in a:
if binary_search(b, t) >= 0:
return t
def binary_search(seq, t):
min = 0
max = len(seq) - 1
while True:
if max < min:
return -1
m = (min + max) // 2
if seq[m] > t:
... |
# Example: querying data in MySQL
import _mysql
db = _mysql.connect(host = "localhost", db="pycourse",
user="python", passwd="python")
db.query("""SELECT name, species FROM pet
WHERE age>=1;
""")
result = db.store_result()
print "Rows",result.num_rows()
print "Fields",resul... |
# by: Kristian Rother, Nils Goldmann
from turtle import *
import time
def move_to(x,y):
up()
setx(x)
sety(y)
down()
def curve(length, depth):
if depth==0:
forward(length)
else:
curve(length*0.333,depth-1)
right(60)
curve(length*0.333,depth-... |
# Convert a dictionary to a JSON-formatted string:
import json
data = {'first': 1, 'second': 'two', 'third': [3,4,5]}
jj = json.dumps(data)
print(jj)
# Convert JSON string back to a Python dictionary:
d = json.loads(jj)
print(d)
|
# Concatenate lists:
import itertools
ch = itertools.chain([1, 2], [3, 4])
print(list(ch))
print(list(itertools.repeat([1, 2], 3)))
# Permutations and combinations of list elements:
p = itertools.permutations([1, 2, 3])
print(list(p))
c = itertools.combinations([1, 2, 3], 2)
print(list(c))
|
# Create a table with characters and numbers.:
import pandas as pd
hamlet = [['Hamlet', 1.76], ['Polonius', 1.52], ['Ophelia', 1.83], ['Claudius', 1.95]]
df = pd.DataFrame(data = hamlet, columns = ['name', 'size'])
print(df)
# Sorted lines by name, filter by minimum size,
# print first two values and write a CSV ... |
"""
SQLite is a very straightforward SQL database.
The data is stored in a single file.
The nice thing about Python SQL modules is
that they have almost the same interface.
"""
import sqlite3
DB_SETUP = '''
CREATE TABLE IF NOT EXISTS babynames (
id INTEGER,
name VARCHAR(32),
gender VARCHAR(1),
amount... |
"""TESTS FOR SHOPPING LISTS"""
import unittest
from datetime import date
from app import shopping_lists
class TestCasesShoppingList(unittest.TestCase):
"""TESTS FOR SHOPPING LIST FN BEHAVIOR"""
def setUp(self):
self._list = shopping_lists.ShoppingLists()
def tearDown(self):
del self._li... |
from collections import deque
materials = list(map(int, input().strip().split()))
magics = deque(map(int, input().strip().split()))
mix_table = dict({150: 'Doll', 250: 'Wooden train', 300: 'Teddy bear', 400: 'Bicycle'})
crafted_presents = dict({'Doll': 0, 'Wooden train': 0, 'Teddy bear': 0, 'Bicycle': 0})
while mate... |
def print_args(*args):
abs_values_list = [abs(num) for num in args[0]]
print(abs_values_list)
input_str = input()
num_list = list(map(float, input_str.split(' ')))
print_args(num_list)
|
def list_manipulator(list_of_numbers, operation, command, *args):
numbers = list(args)
if operation == 'add' and command == 'beginning':
for _ in range(len(numbers)):
list_of_numbers.insert(0, numbers.pop())
elif operation == 'add' and command == 'end':
for _ in range(len(number... |
from collections import deque
def check_left_side_is_smaller(left_sublist, right_sublist):
left_avg = sum(left_sublist) / len(left_sublist)
right_avg = sum(right_sublist) / len(right_sublist)
return left_avg < right_avg
def check_right_side_is_smaller(central_value, right_sublist):
right_avg = sum(r... |
STEP_RIGHT_SIZE = 3
STEP_DOWN_SIZE = 1
INPUT_MAP_FILENAME = "input.txt"
TREE = "#"
def load_input_map(input_map_filename: str = INPUT_MAP_FILENAME):
with open(input_map_filename, 'r') as f:
return [line.strip() for line in f]
def count_trees_in_path(map,
step_right_size: int = ... |
import re
import urllib.request
# Open the file you want to get your URLs from
file = open('file', "r")
# You have to add your own regex in the findall() function (I knew what I was looking for myself and made a regex for that
# not sure if this actually works with any given regex and file, as I made this for ... |
# Eleftheria Briakou
import argparse
import logging
import numpy as np
import matplotlib.pyplot as plt
class Neural_Network:
def __init__(self, layers, nodes, eta, iterations, active, problem):
'''
Initialize a neural network
:param layers: number of layers
:param nodes: number of... |
# Rock, Paper, Scissors
import random
while True:
user_hand = input("Enter your move (Rock, Paper, Scissors): ")
cap_user_hand = user_hand.capitalize()
moves = ["Rock","Paper","Scissors"]
comp_move = random.choice(moves)
print("You chose " + cap_user_hand + ", the computer chose " + comp_move + ... |
c = 'ક'
print("before :",c)
if c == 'ક':
c = 'a'
print("after :",c)
|
from tkinter import *
window = Tk()
## 함수 선언 부분 ##
def myFunc() :
if var.get() == 1 :
label1.configure(text = "파이썬")
elif var.get() == 2 :
label1.configure(text = "C++")
else :
label1.configure(text = "Java")
## 메인 코드 부분 ##
var = IntVar()
rb1 = Radiobutton(window, text = "파이썬"... |
#!/usr/bin/python
from ctypes import *
from time import sleep #for multithreading
import threading, re
# 2.1 CTypes: Write a function which takes two arguments: title and body
# Create A messageBox with those arguments (not possible in Linux, just pretend)
def python_message_box(title = "", body=''):
return
# 2.2 C... |
"""Write a function that takes two parameters, an array and some number.
The function should determine whether any three numbers in the array add up to the number.
If it does, the function should return the numbers as an array. If it doesn’t, the function should return -1.
Example
Input: [1, 2, 3, 4, 5, 6], 6
Output: [... |
"""Write a function that takes an array of positive integers.
The function should calculate the sum of all even and
odd integers and return an array containing the sums.
The first index in the returned array should hold the sum of the even integers
and the second index should hold the sum of the odd integers."""
def ... |
class NeighboringNodes(object):
def __init__(self, size, debug=False):
self.size = size
self.debug = debug
def build_grid(self):
i = 0
grid = []
for y in range(self.size):
grid.append([])
for x in range(self.size):
node = {'x': x,... |
import os
from typing import Dict
class Unigrams:
""" A class representing token: freq struct """
def __init__(self, unigrams: Dict):
self.unigrams = unigrams
class UnigramParser:
"""
A class creating unigrams statistics
basing on data/poleval_2grams.txt file
"""
DATA_PAT... |
#задание1
import numpy as np
a = np.array([[1, 6],
[2, 8],
[3, 11],
[3, 10],
[1, 7]])
print(a)
print(a.mean())
b = (a[0:, 0])
c = (a[0:, 1])
d = b.mean()
r = c.mean()
mean_a = [d, r]
#задание2
a_centered = a - mean_a
#задание3
a_centered_sp = a_centered[0:, 0] ... |
from math import sqrt
def standard_deviation(lst, population=True):
"""Calculates the standard deviation for a list of numbers."""
num_items = len(lst)
mean = sum(lst) / num_items
differences = [x - mean for x in lst]
sq_differences = [d ** 2 for d in differences]
ssd = sum(sq_differences)
... |
# Take the input value to start with
input_string = input("Enter a 5 digit number")
while True : #keep the loop running till user doesnt input the valid input
if len(input_string) == 5: # Check if the input lengeth is equal to 5
try: # try statement because if user inputs alphabets istead of number we will ... |
card_values = {
"2": 2, "3": 3, "4": 4, "5": 5, "6": 6,
"7": 7, "8": 8, "9": 9, "10": 10,
"Jack": 11, "Queen": 12, "King": 13, "Ace": 14}
hand_cards = []
while len(hand_cards) < 6:
card = input()
if card in card_values.keys():
hand_cards.append(card)
summed_values = 0
for card in hand_card... |
# The following line creates a dictionary from the input. Do not modify it, please
test_dict = json.loads(input())
min_value = min(test_dict.values())
max_value = max(test_dict.values())
min_key = ""
max_key = ""
for key, value in test_dict.items():
if value == min_value:
min_key = key
elif value == ma... |
entrada = input()
a = 0
b = 0
for e in range(0, len(entrada),2 ):
if entrada[e] == 'A':
a = a + int(entrada[e+1])
else:
b = b + int(entrada[e+1])
if a > b:
print('A')
else:
print('B') |
message=""
#function to accept the message from the user
def test_function(entry):
print("This is the entry:",entry)
global message
message=entry
pos=0
neg=0
nu=0
#function to fact check
def get_news(message):
import numpy as np
import matplotlib.pyplot as plt
import pandas as p
... |
class Cell():
"""
represents a singular cell
"""
def __init__(self,initial_state:bool = False) -> None:
if type(initial_state) != bool:
raise ValueError(f"Invalid initial_state {initial_state!r}")
self.initial_state = initial_state
self.state = initial_state
def flip(self) -> bool:
"""
kills a living ... |
import datetime
import time
if __name__ == '__main__':
print(time.strftime('%Y.%m.%d %H:%M:%S ',time.localtime(time.time())))
dayOfWeek = datetime.datetime.now().isoweekday() ###返回数字1-7代表周一到周日
day_Week = datetime.datetime.now().weekday() ###返回从0开始的数字,比如今天是星期5,那么返回的就是4
day = datetime.datetime.now()
... |
# Abrir archivo 14.POO para ver detalles
class Persona():
def __init__(self, nombre, edad, direccion):
self.nombre=nombre
self.edad=edad
self.direccion=direccion
def descripcion(self):
print("Nombre: ", self.nombre, " edad: " , self.edad, " Direccion: ", self.direccion)
clas... |
print("Welcome to Elpollotonios Functions Calculator")
num1 = int(raw_input("Give me a number: "))
num2 = int(raw_input("Give me a number: "))
def myAddFunction(add1, add2):
sum = add1 + add2
return sum
print("Here is the sum: " + str(myAddFunction(num1, num2)))
def mySubFunction(sub1, sub2):
difference ... |
class Sudoku:
def __init__(self, board):
self.board = board
def is_safe(self, row, col, number):
if number == '' or number == 0:
return False
# Check Horizontally
for i in range(9):
if not i == col:
if self.board[row][i] == n... |
class Solution:
def generateParenthesis(self, n):
ans = []
def backtrack(s,left,right):
if len(s) == 2*n:
ans.append(s)
if left < n:
backtrack(s+'(',left+1,right)
if right < left:
backtrack(s+')',left,right+1)
... |
f = open("/Users/we2423hd/Documents/untitled5/rosalind_dna.txt")
def countNucleotide():
thymine = 0
cytosine = 0
guanine = 0
adenine = 0
next = f.read(1)
while next != "":
if(next == "T"):
thymine += 1
elif(next == "C"):
cytosine += 1
elif(nex... |
import ft_len as lenn
def ft_even_place(str):
a = ""
for i in range(lenn.ft_len(str)):
if i % 2 == 1:
a += str[i]
return a
|
from queue import *
def make_tree(g, t, p):
n = len(g)
visited = [False] * (n+1)
visited[1] = True
q = Queue(maxsize=0)
q.put(1)
while not q.empty():
curr = q.get()
for v in g[curr]:
if not visited[v]:
visited[v] = True
p[v] = curr
t[curr].append(v)
q.put(v)
def compute_sizes(tree, size... |
#!/usr/bin/env python
# 2017.05.01 23:00
# this program was wrote for greping lines from a file based on certain gene names that provided in another file.
import argparse
import csv
import re
def _main():
greper=argparse.ArgumentParser(description="Greping lines from a file (search file) based on certain gene na... |
def morral(tamanoMorral, pesos, valores, n):
if n == 0 or tamanoMorral == 0:
return 0
if pesos [n-1] > tamanoMorral:
return morral(tamanoMorral, pesos, valores, n-1)
return max(valores[n-1] + morral(tamanoMorral - pesos[n-1], pesos, valores, n-1),
morral(tamanoMorral, p... |
from Rectangle import *
from Point import *
class Quadtree():
def __init__(self, boundary, n): # boundary is a Rectangle
self.boundary = boundary
# how big is the quadtree? when do I need to subdivide?
# this is a job for capacity
self.capacity = n
# store... |
import time
import webbrowser
import tkinter
from tkinter import messagebox
ideal_breaks = 3
breaks_taken = 0
while (breaks_taken< ideal_breaks):
time.sleep(2*60*60)
webbrowser.open("https://www.youtube.com/watch?v=5qap5aO4i9A")
time.sleep(60*15)
#increase the brakes taken
breaks_taken += 1
... |
# 프로그래머스 타겟넘버
# 문제링크 : https://programmers.co.kr/learn/courses/30/lessons/43165
# 정확성 : 100
# 이 문제는 주어진 리스트의 숫자들를 적절히 더하거나 빼서 타겟넘버를 만드는 문제입니다.
# 더하고 빼는 과정이 복잡해서 리스트의 모든 수를 더하고 그 값에서 타겟넘버만큼 도달하기 위해
# 주어진 숫자들을 2씩 곱해서 빼보면서 살펴보았습니다.
# 리스트를 내림차순으로 정렬하여 큰 수부터 빼보며 비교하는 것이 편하여 내림차순으로 정렬하였습니다.
# answer는 주어진 리스트로 더하거나 빼서 타겟넘... |
# problem URL -> https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV15OZ4qAPICFAYD
import itertools
def main():
testcase_count = int(input().strip())
for testcase_num in range(1, testcase_count + 1):
cusomter_count = int(input().strip())
location_list = list(map(int, input().strip().... |
# 문제 url -> https://programmers.co.kr/learn/courses/30/lessons/43165
class Tree:
def __init__(self, target_number):
self.tree_body = [0]
self.target_number = target_number
self.count = 1 # 이진 트리 만들때 사용
# 이진 트리 만들기
def make_tree(self, numbers):
for number in numbers:
... |
def isOpen(ch):
return ch == '(' or ch == '[' or ch == '{' or ch == '<'
def isMatch(ch1, ch2):
if ch1 == '(' and ch2 == ')':
return True
elif ch1 == '[' and ch2 == ']':
return True
elif ch1 == '{' and ch2 == '}':
return True
elif ch1 == '<' and ch2 == '>':
return Tru... |
def printInorder(root):
if root:
printInorder(root.right)
print(root.data, end=" ")
printInorder(root.left)
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.data, end=" "),
def printPreorder(root):
if root:
print(root.data, end=" "),
pri... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 17:54:33 2019
@author: Lavi
"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def push(self,new_data):
new_node=Node(ne... |
import config
from child_info import ChildInfo
import textwrap as tr
import prompts
import user_input
import save_story
def delete_child_option() -> bool:
"""Let's the user choose if child data should be deleted
Returns:
bool: True if data should be deleted, False otherwise
"""
delete = user_... |
#!/usr/bin/python
# Strings and Lists
# http://rosalind.info/problems/ini3/
def slicing(text,a,b,c,d):
first = text[a:b+1]
second = text[c:d+1]
return first, second
string = "gzEYWRFMzUxWjBiBBDvB0DzHScdVR7lYJRCK8lJPxP4H7jFelisTIT1XZcA5nyecB6Jacanthinura2C4ZGHr5uz0dfiwbj5tVazOSivn7D2dHvILgdk5e4CpdLKkv... |
def mergesort(seq):
if len(seq)<=1:
return seq
mid = len(seq) // 2
left = mergesort(seq[:mid])
right = mergesort(seq[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
... |
"""
This program generates passages that are generated in mad-lib format
Author: Katherin
"""
# The template for the story
STORY = """Esta manhã eu %s acordei me sentindo %s. Vai ser um dia %s! Do lado de fora, um monte de %ss protestavam para manter %s nas lojas. Eles começaram a comer
%ss ao ritmo do %s, o... |
#names = ["Adam","Alex","Mariah","Martine","Columbus"]
#for name in names:
# print (name)
#webster = {
# "Aardvark" : "A star of a popular children's cartoon show.",
# "Baa" : "The sound a goat makes.",
# "Carpet": "Goes on the floor.",
# "Dab": "A small amount."
#}
#for item in webster:
# print (... |
#my_list = [1,9,3,8,5,7]
#for number in my_list:
# print (2 * number)
#start_list = [5, 3, 1, 2, 4]
#square_list = []
#for number in start_list:
# square_list.append(number ** 2)
#square_list.sort()
#print (square_list)
# Assigning a dictionary with three key-value pairs to residents:
#residen... |
"""
O Grande Investidor, Jogo que você começa com 100000,00 e investe em empresas. Vai Gerar uma porcentagem de -100% ate 100% do
valor que vc investiu, e retornara na sua conta, com 15 perguntas sobre empresas.
"""
from random import randint
from time import sleep
bemvindo = {
"ola" : "#$# Bem Vindo ao Jogo #$#",
"b... |
from random import randint
board = []
for tj in range(5):
board.append(["O"]*5)
def printboard(boardin):
for row in board:
print (" ".join(row))
printboard(board)
def randomrow(boardin):
return randint(0,len(boardin) - 1)
def randomcol(boardin):
return randint(0,len(boardin)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
Simple Bot to reply to Telegram messages.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is... |
"""
File containing simple function that returns log object
"""
import os
import warnings
import logging
from logging import handlers
def setup_logger(log_file_path):
"""
Takes log file name as input are returns a logger object
TODO:
"""
logger = logging.getLogger(log_file_path)
logger.setLe... |
import pandas
mydatas = {
"unames" : ['Ali', 'Ahmet', 'Mehmet', 'Cemil', 'Kerim'],
"age" : [21,30,53,45,34],
"price": [1700,2200,3400,1100,1000],
"currency" : ["TRY", "USD","TRY","USD","USD"],
"created_at" : ["12.11.2019", "11.02.2020", "09.07.2019", "09.09.2018", "02.01.2017"]
}
df = pandas.DataF... |
# Python Object Oriented Programming
class Employee:
raise_amount = 1.04
employee_count = 0
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first.lower() + '.' + last.lower() + '@company.com'
Employee.emplo... |
import os
import time
class Car:
def __init__(self, custom_speed):
self.position = 0
self.speed = custom_speed
def drive(self):
self.position += self.speed
def print_info(self):
print("Car is current at:", self.position, "with an speed of:", self.speed, end='\r')
... |
import validate
import solve
import json
import os
def main():
#fetching the sudoku
path = os.path.abspath("sudoku.json")
with open(path) as data_:
data = json.load(data_)
sudoku = data['sudoku']
# validate the sudoku
validation = (validate.run(sudoku)).Validate()
if validation i... |
number = input('输入要下载的视频序号:').split('.')
print(number)
print(type(number))
print([infors[int(i) - 1][-1] for i in number])
# 2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17
# 低调学习的人华清远见 |
# python3
class Node:
def __init__(self, key, next=None):
self.key = key
self.next = next
class Stack:
def __init__(self):
self.head = None
def push(self, key):
self.head = Node(key, self.head)
def pop(self):
if not self.head:
print('ERROR: Empty... |
# python3
import random
def naive_lcm(a, b):
for i in range(1, a*b + 1):
if i % a == 0 and i % b == 0:
return i
return a*b
def lcm(a, b):
if b > a:
a, b = b, a
for i in range(a, a*b + 1, a):
if i % b == 0:
return i
return a*b
def euclid_gcd(a,... |
# python3
import sys
import threading
sys.setrecursionlimit(10**6) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class Node:
def __init__(self, key=None, left=None, right=None):
self.key = key
self.left = left
self.right = right
def in_... |
# python3
import sys
import threading
sys.setrecursionlimit(10**6) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class Node:
def __init__(self, key=None, left=None, right=None):
self.key = key
self.left = left
self.right = right
def in_... |
class Node:
def __init__(self, data=None):
self.data=data
self.next=None
def check_palindrome_ll(head, root):
if root == None:
return True
comp_val = None
if root.next == None:
comp_val = 1
else:
comp_val = check_palindrome_ll(head, root.next)
if not co... |
class Queue:
def __init__(self):
self.data = []
def enqueue(self, data):
self.data = self.data + [data]
def dequeue(self):
if len(self.data) > 0:
dequed = self.data[0]
self.data = self.data[1:len(self.data)]
return dequed
... |
import requests
from bs4 import BeautifulSoup
r = requests.get('https://pt.stackoverflow.com/')
if r.status_code == 200: # Retorno da request
#print('Entramos!')
#print(r.content) Utilizamos o content pois ele é binário, o necessário para fazer o soup, text é unicode
soup = BeautifulSoup(r.content, ... |
#Inc11prog.py
'''
value-return function with 3 parameters n1, n2 ,n3 passed in
'''
def average(n1,n2,n3):
print("Entering: ", average.__name__ + '()')
return (n1+n2+n3) / 3.0
'''
main: main function of program
'''
def main():
avg = 0.0
print("average before function call:", avg)
avg = average(1,2,... |
#Example of bin to hex
#refer here http://www.wikihow.com/Convert-Binary-to-Hexadecimal for algorithm
#create a list to look up hex vales
hex_list = ['0','1','2','3',
'4','5','6','7',
'8','9','A','B',
'C','D','E','F']
bin_num = input("Please enter a binary number:")
#to make the ... |
#create an empty basestring
word = ""
#assign a string a value from user input
word = input("Please enter a string: ")
#ensure we don't compare word to a list of capitial letters
word_lower = word.lower()
#Recall how we determined odds/evens on a sequential increasing list of ints starting at 0
eoth_cap_string = ""
... |
# In-Class Program 7 Examples
print("Convert integer to binary using string.")
num = int(input("Please enter a integer: "))
# create empty string to hold bits
bin_num = ''
# while we have not divided the number down to 0
while num != 0:
bin_num += str(num % 2) # get the bit per iteration
num = int(num / 2) ... |
def check_legal_driver(age, country):
"""Asks user for their age and determines whether they are old enough to drive
Args:
age: age of the individual
country: country in which they wish to drive
Returns:
string: If country is recognized, returns whether the individual is old
... |
"""
Defines and implements a square footage calculator class
"""
class Calculator():
"""
Representation of an area calculator that takes two numbers and multiplies them together
Attributes:
len: A float indicating the length of a surface
width: A float indicating the width of a surface
... |
"""
Defines a class that helps troubleshooting common car issues
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from util_functions.utils import user_inputs
class Node():
"""Represents a node in a tree object
Attributes:
left (o... |
"""
Defines the primary functions used by the application.
Functions:
startup: Check for data in local storage. If it exists, load it into a new PersonalInventory
class instance. Otherwise initiate a new, blank, instance of the same class.
prompt: Prompts the user for an action and returns the selectio... |
"""Defines the database for the app"""
from flask import current_app as app
from flask import g as flask_g
from flask.cli import with_appcontext
from sqlalchemy.dialects.postgresql import JSON
from . import db
from datetime import datetime
class User(db.Model):
# SQLAlchemy adds an implicit constructor to all mode... |
"""
Defines a StatsCalculator class and instantiates it
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from util_functions.utils import user_inputs
class StatsCalculator():
"""Represents a statistical summary calculator
Attributes:
... |
"""
Defines a function to check for anagrams
"""
def is_anagram(first_string, second_string):
"""Compares two strings to determine whether they are anagrams
Args:
str1 (str): A string to be compared
str2 (str): A second string
Returns:
(bool): True/False indication of whether the ... |
"""
Class and functions for calculating BMI Calcs
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from util_functions.utils import user_inputs
class BMICalculator():
"""A representation of a BMI calculator
Attributes:
HEALTHY_BMI:... |
"""
Arrays don't have to be hard-coded. You can take
user input and store it in an array and then work
with it.
Create a program that picks a winner for a contest or
prize drawing. Prompt for names of contestants until
the user leaves the entry blank. Then randomly
select a winner.
___________________
Example Output... |
"""
Helper functions used during the application.
Functions:
_get_item_name: Prompts user for the name of an item
_get_serial: Prompts user for the serial number of an item
_get_value: Prompts user for the value of an item. User input must be numeric
"""
import sys
import os
sys.path.append(os.path.dirnam... |
def lis_brg(x,y=[]):
y.append(x)
return y
z=lis_brg(134)
print(z)
print(lis_brg(3))
print(lis_brg(90))
#defined function also can be called using keywords arguement
def kakaktua(volt, state = "stiff", action = "lari", type = "malaysian green"):
print("-- Kakak tua ni takkan ", action, end = '... |
#Written by Allif Izzuddin bin Abdullah
#github : allifizzuddin89
#replace data
#use replace if there is some random unknown value instead of NaN
import pandas as pd
import numpy as np
df = pd.read_csv("weather_data2.csv")
print(df) #shows -99999, -88888 means unknown value
#replace -99999, -88888 using numpy
new_... |
#Written by Allif Izzuddin bin Abdullah
#github : allifizzuddin89
#TIME SERIES ANALYSIS 2
#Study case : KLSE:IHH
#ununiformity input data
#use to_datetime to convert date into single format
import pandas as pd
date = ['2020-01-07','Jan 7,2020','01/07/2020','2020.01.07','2020/01/07','20200107']
d1 = pd.to_datetime(... |
#Written by Allif Izzuddin bin Abdullah
#github : allifizzuddin89
#TIME SERIES ANALYSIS 1
#Study case : KLSE:IHH
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('klse.ihh.csv')
print(df)
#another method to import stock historical data is via yfinance and pa... |
#Written by Allif Izzuddin bin Abdullah
#github : allifizzuddin89
#Numpy exercise 1
import numpy as np
#initialize array
a = np.array([1,2,3])
print(a)
b = np.array([[5.6,3.3,7.8],[2.0,5.3,4.3]])
print('\n',b)
#get dimension info
print('\n',a.ndim)
print('\n',b.ndim)
#get shape info
print('\n',a.shape) #row x co... |
#Written by Allif Izzuddin bin Abdullah
#github : allifizzuddin89
#subplot
import matplotlib.pyplot as plt
import random
from matplotlib import style
#plot style, font, width etc..
style.use('fivethirtyeight')
fig = plt.figure()
def create_plots():
xs = []
ys = []
for i in range(10):... |
#Written by Allif Izzuddin bin Abdullah
#github : allifizzuddin89
#TIME SERIES ANALYSIS 7
#Study case : KLSE:IHH
#2 type of DateTime Objects on Python:
#1.Naive no timezone awareness
#2.Time zone aware datetime
#pytz
import pandas as pd
df = pd.read_csv('klse.ihh.csv', index_col='Date',parse_dates=['Date'])
print(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.