text stringlengths 37 1.41M |
|---|
#using python 3.6.4
import datetime
#import calendar
def last_day_of_month(any_day):
next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # this will never fail
return next_month - datetime.timedelta(days=next_month.day)
CurrentDate = datetime.date.today()
print("Η σημερινη ημερομηνια ειναι... |
# Generators
def generator_func(num):
for i in range(num):
# after yielding i, it pauses and remembers the last yield
yield i
g = generator_func(10)
# when next(g) is called, the generator_func will pick up from last yield and yields next value until it reaches the last index of range
# when t... |
from functools import reduce
# 1. Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included).The numbers obtained should be printed in a comma-separated sequence on a single line.
def find_divisible_by_7(start_num, end_num):
# no pa... |
""" Initialize data structures """
CFG = {} # Context Free Grammar
CYK = [] # CYK Matrix
""" Auxiliar Methods """
def print_matrix( cyk ):
""" Print current state of the Matrix """
for row in cyk:
print row
print "=" * 20
def populate_matrix( cyk, w ):
""" Initialize Matrix """
for ... |
#!/usr/bin/env python3
#
import sys
import time
_description_ = """
Import time and sleep for one second to provide a countdown.
Use for loop. Call a function to to print the countdown.
"""
_author_ = """Ian Stewart - December 2016
Hamilton Python User Group - https://hampug.pythonanywhere.com
CC0 ... |
#!/usr/bin/env python3
#
print("The window creation has been appended to configure a red background")
import tkinter
tkinter.Tk().configure(background="red")
# Add the following delay mechanism, so the Tk Window can be observed...
input("Hit Return key to exit")
"""
The tkinter.Tk() to launch a window is ap... |
#!/usr/bin/env python3
#
import sys
import math
_description_ = """
Locate prime numbers. Use recursive division up to the square root of
the integer being tested for being a prime
int(math.sqrt(integer_under_test))
Provide statistics and better listing.
"""
_author_ = """Ian Stewart - December 201... |
#!/usr/bin/env python3
#
import sys
_description_ = """
Use input () function to get data from the User at the command line.
Use while True loop to ensure data is entered or data is of the desired
type.
"""
_author_ = """Ian Stewart - December 2016
Hamilton Python User Group - https://hampug.python... |
# RADIUS = 10
import math
def input_radius():
"""Get User input from the console."""
radius = input("Enter the radius of the circle: ")
return float(radius)
def calculate_circle_area(radius):
"""Supplied with the radius, calculate the area of a circle."""
area = math.pi * radius ** 2
... |
#!/usr/bin/env python3
#
from tkinter import *
from tkinter import ttk
class MainWindow(ttk.Frame):
"""Create the main window"""
def __init__(self, parent):
ttk.Frame.__init__(self, parent)
self.parent = parent
self.parent.title("Fibonacci series")
self.label = ttk.... |
#!/usr/bin/env python3
#!
print("Fibonacci series...")
fibonacci_list = [0,1]
for i in range(1,15):
fibonacci_list.append(fibonacci_list[i-1] + fibonacci_list[i])
print(fibonacci_list)
input("Hit Return key to exit")
"""
Fibonacci series with .py extension - Uses console window,... |
# Reject a string that won't convert to a floating point value.
# If invalid data entry, then ask for the data again.
def input_radius(prompt):
"""Get User input from the console. Must be integer or floating point"""
while True:
radius = input("Enter the radius of the circle [{}]: ".format(prompt))
... |
#!/usr/bin/env python3
#
import tkinter
print("The geometry() function to modify the Windows dimensions and position.")
# Use tkinters Tk()
tkinter.Tk().geometry("400x100+200+500")
tkinter.mainloop()
"""
Set the Windows geometry. Values are in pixels.
Note: There can be no spaces in the string. E.g.
.geom... |
#!/usr/bin/env python
import random
import sys
import os
import codecs
from utils import *
from Crypto.Cipher import AES
BLOCK_SIZE = 16
IV = b'This is easy HW!'
# HW - Utility function
def blockify(text, block_size=BLOCK_SIZE):
"""
Cuts the bytestream into equal sized blocks.
Args:
text should b... |
import random
def _random_item(collection):
return collection[ random.randrange( len(collection) ) ]
class Codes:
background = 0
foreground = 1
temporary = 2
forbidden = 3
class Path:
def __init__(self, position, parent = None):
self.position = position
self.par... |
# -*- coding: UTF-8 -*-
#使用梯度下降解决线性回归
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
points_num = 100
vectors = []
#用numpy的正太随机分布函数生产100个点
#y = 0.1 * x + 0.2
for i in xrange(points_num):
x1 = np.random.normal(0.0, 0.66)
y1 = 0.1 * x1 + 0.2 + np.random.normal(0.0, 0.04)
vector... |
# Usage: python a2_bonus_checker.py 'your_answer_here.py'
# 'your_answer_here.py' should contain function can_be_combined()
import sys
import random
import a2
import a2_bonus
LOWER_LENGTH = 10
UPPER_LENGTH = 50
LOWER_FRAGMENTS = 3
UPPER_FRAGMENTS = 8
def get_complement(nucleotide):
""" (str) -> str
Return ... |
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... |
import a1
import unittest
class TestSwapK(unittest.TestCase):
""" Test class for function a1.swap_k. """
def test_swap_k_1(self):
""" Test empty list """
L = []
k = 0
a1.swap_k(L, k)
expected = []
self.assertEqual(L, expected)
def test_swap_k_2(self):
... |
# Do not import any modules. If you do, the tester may reject your submission.
# Constants for the contents of the maze.
# The visual representation of a wall.
WALL = '#'
# The visual representation of a hallway.
HALL = '.'
# The visual representation of a brussels sprout.
SPROUT = '@'
# Constants for the directio... |
class Predictor:
"""An interface for all expected predictor behaviour."""
def define_and_fit(self, model_file):
"""
Interface for defining and fitting a predictor.
Must be implemented for each new predictor you want to use.
:param model_file: string of the file path where the m... |
class InputProcessor():
def __init__(self, inputToProcess, chessNotation="simplified"):
self.inputToProcess = inputToProcess
self.chessNotation = chessNotation
self.pieceAbbreviations = ("p", "r", "n", "b", "k", "q")
def processInput(self, board, side):
# Heavily simplified ... |
sum = 0
for i in range(101):
sum += i
print('Summen av de 100 første tallene er', sum)
produkt = 1
i = 1
while produkt < 1000:
i += 1
produkt *= i
print('Løkken kjørte', i, 'ganger og produktet ble', produkt)
tall1 = int(input('Skriv inn et tall: '))
tall2 = int(input('Skriv inn et nytt tall: '))
produk... |
n = int(input('Skriv inn et tall: '))
r = int(input('Skriv inn et tall: '
''))
sum = 0
while -1 < r < 1:
|
# -*- coding:utf-8 -*-
import threading
import _thread
import time
"""
1.线程
1.1 创建一个线程
1.2 自定义线程类
1.3 线程安全之使用Lock
1.4 线程安全之使用RLock
1.5 线程安全之使用信用量
1.6 线程安全之使用条件
1.7 线程安全之使用事件
"""
# 1.1 创建一个线程
# def func(i):
# print("%d threading is running" % i)
#
#
# threads = [... |
# -*- coding:utf-8 -*-
from abc import ABCMeta, abstractclassmethod
"""
策略模式之一:
场景: 小明离职,同事选择交通工具去聚餐
"""
class Vehicle(metaclass=ABCMeta):
"""
策略抽象基类
"""
@abstractclassmethod
def running(cls):
pass
class Walk(Vehicle):
"""
步行策略类
"""
def running(cls):
... |
#Estrutura de Dados: Fila
#FIFO: First In, First Out
class Fila:
def __init__(self): # Construtor da classe
self.fila = []
def __repr__(self): # Retorna uma representação visual do objeto
return self.fila.__repr__()
def tamanho(self): # Retorna o tamanho da fila
return len(self.fil... |
#take input list
print("How many numbers in your list:");
num = 0;
try:
num = int(input())
except TypeError:
print("not an integer defaulting to 10 numbers");
num = 10;
li = []
for i in range(num):
li.append(int(input()))
#count inversion
count = 0
# 4 8 20 6 7 9 = 4 6 7 8 9
def numMergeInver... |
x = int(input("How long do you sleep at night?"))
y = int(input("How long do you sleep during the day?"))
print (x * 60 + y) |
a = int(input())
b = int(input())
c = int(input())
d = int(input())
print("\t", end="")
for j in range(c, d + 1):
print("\t", j, sep="", end="")
for i in range(a, b+1):
print("\n", i, end="")
for x in range(c, d+1):
print("\t", (i * x), end="")
print(end="") |
x = str(input())
sum1 = int(x[0]) + int(x[1]) + int(x[2])
sum2 = int(x[3]) + int(x[4]) + int(x[5])
if sum1 == sum2:
print("Счастливый")
else:
print("Обычный") |
#!/usr/bin/env python3
import numpy as np
N = 2**np.linspace(3, 8, 6, dtype=int)
OSR = np.linspace(1, 8, 8, dtype=int)
print(" ",N)
def f(M, levels):
return [max(1, int(c)) for c in np.floor(np.divide(levels, 2**(M-1)))]
ans = []
for M in OSR:
ans.append(f(M, N))
print(M, f(M, N))
|
import random,methods,os,subprocess
import yfinance as yf
import pandas as pd
import csv
import matplotlib.pyplot as plt
subprocess.Popen('python interest.py')
while True:
print()
print("Welcome to the bank!")
print()
print("1 to create a new account,2 to check balance,3 to deposit, 4 to tra... |
password = "contraseña"
contraseña_usuario = input("introduce contraseña")
if password.capitalize() == contraseña_usuario.capitalize() :
print("contraseña correcta")
else:
print("contraseña incorrecta")
|
from collections import defaultdict
import sys
def mc_evaluation(policy, env, num_episodes, discount_factor=1.0):
"""
First-visit MC Policy Evaluation. Calculates the value function
for a given policy using sampling.
Args:
policy: A function that maps an observation to action probabilities.
env: OpenA... |
import pygame
class Bullet:
bulletX: float
bulletY: float
def __init__(self, xCord, yCord):
self.bulletX = xCord
self.bulletY = yCord
class missile(Bullet):
bullet_Img: pygame.image
bullet_speed: int
bullet_dir: bool
bullet_position:int
def __init__(self, xCord, yCord... |
##########--------------------------------------------- 2 sum problem ----------------------------------------------##########
from datetime import datetime
# Class to implement algorithm for 2 sum problem
class twoSum:
# Initialising class variable
def __init__(self):
self.data = []
self.sum... |
my_foods=['pizza','falafel','carrot cake']
my_foods.append('apple')
print("我喜欢的食物有:")
for food in my_foods:
print(food) |
person_information1 = {'first_name': '尚', 'last_name': '若冰', 'age': '20', 'city': '昆明'}
person_information2 = {'first_name': '倪', 'last_name': '尔', 'age': '19', 'city': '长沙'}
person_information3 = {'first_name': '张', 'last_name': '颍', 'age': '19', 'city': '江西'}
people = [person_information1, person_information2, person... |
river = {'nile': 'egypt', 'yellow river': 'China', 'Yangest river': 'China'}
river_name = ['nile', 'yellow river', 'Yangest river']
for name in river.keys():
print(name.title())
if name in river_name:
print("The " + name.title() + " through " + river[name].title())
for river_name in river.keys():
pr... |
animals = ['dog', 'cat', 'pig']
for pet in animals:
print("A" + pet + "would make a great prt!")
print("Any of these animals would make a great pet!")
|
"""
Two words are blanagrams if they are anagrams but exactly one letter has been substituted for another.
Given two words, check if they are blanagrams of each other.
Example
For word1 = "tangram" and word2 = "anagram", the output should be
checkBlanagrams(word1, word2) = true;
For word1 = "tangram" and word2 = "p... |
#!/bin/env python
class Animal(object):
pass
class Dog(object):
def __init__(self): pass
class Cat(object):
def __init__(self): pass
doggy = Dog()
assert type(doggy) == Dog
# Animal: fail
assert type(doggy) == Animal
print type(doggy)
# Cat: fail
assert type(doggy) == Cat
# int: fail
assert type(dogg... |
def bubble_sort(items):
for pass_num in range(len(items)-1,0,-1):
for i in range(pass_num):
if items[i]>items[i+1]:
temp = items[i]
items[i] = items[i+1]
items[i+1] = temp
return items
def merge_sort(items):
if len(items) <= 1:
r... |
print("===LIST TEMAN DHEA===")
nama_teman = ['Alip', 'Audi', 'Ambon', 'Ayak', 'Echa', 'Rizal', 'Duha', 'Vika', 'Riki', 'Nina']
#isi indeks 4,6, dan 7
print("\n",nama_teman[4],"\n", nama_teman[6],"\n", nama_teman[7])
#mengganti nama teman di list 3,5, dan 9
nama_teman[3] = 'Alyn'
nama_teman[5] = 'Hasna'
nama_teman[9] = ... |
def getMinimumIndex (list):
minIndex = 0
for i in range (len(list)):
if list [i] < list [minIndex]:
minIndex = i
return minIndex
initialList = eval(input())
sortedList = []
for i in range (len(initialList)):
minIndex = getMinimumIndex(initialList)
sortedList.append(init... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Sudoku Solver.py
# Creation Time: 2017/7/2
###########################################
'''
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by ... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Reverse Bits.py
# Creation Time: 2018/3/5
###########################################
'''
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented i... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Count of Smaller Numbers After Self.py
# Creation Time: 2017/9/1
###########################################
'''
You are given an integer array nums and you have to return a new counts arra... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Subsets.py
# Creation Time: 2017/7/11
###########################################
'''
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not con... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Palindrome Linked List.py
# Creation Time: 2018/2/17
###########################################
'''
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it ... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Find K-th Smallest Pair Distance.py
# Creation Time: 2018/4/22
###########################################
'''
Given an integer array, return the k-th smallest distance among all the pairs. ... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Range Addition II.py
# Creation Time: 2018/1/8
###########################################
'''
Given an m * n matrix M initialized with all 0's and several update operations.
Operations are... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Path Sum II.py
# Creation Time: 2017/7/20
###########################################
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Ugly Number.py
# Creation Time: 2018/3/22
###########################################
'''
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numb... |
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Unique Binary Search Trees II.py
# Creation Time: 2018/5/16
###########################################
'''
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Length of Last Word.py
# Creation Time: 2017/7/6
###########################################
'''
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', retur... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Count Numbers with Unique Digits.py
# Creation Time: 2017/9/8
###########################################
'''
Given a non-negative integer n, count all numbers with unique digits, x, where 0... |
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Container With Most Water.py
# Creation Time: 2017/6/23
###########################################
'''
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
n vertical lin... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: K-th Symbol in Grammar.py
# Creation Time: 2018/2/9
###########################################
'''
On the first row, we write a 0. Now in every subsequent row, we look at the previous row a... |
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Swap Nodes in Pairs.py
# Creation Time: 2017/6/30
###########################################
'''
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should retur... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Find Minimum in Rotated Sorted Array.py
# Creation Time: 2017/7/30
###########################################
'''
Suppose an array sorted in ascending order is rotated at some pivot unknown... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Different Ways to Add Parentheses.py
# Creation Time: 2017/8/25
###########################################
'''
Given a string of numbers and operators, return all possible results from com... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name:Set Matrix Zeroes.py
# Creation Time: 2017/7/10
###########################################
'''
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
'... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Add Binary.py
# Creation Time: 2017/7/7
###########################################
'''
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Retu... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: 2 Keys Keyboard.py
# Creation Time: 2018/1/5
###########################################
'''
Initially on a notepad only one character 'A' is present. You can perform two operations on this... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Binary Tree Right Side View
# Creation Time: 2017/8/13
###########################################
'''
Given a binary tree, imagine yourself standing on the right side of it, return the valu... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Majority Element.py
# Creation Time: 2018/3/5
###########################################
'''
Given an array of size n, find the majority element. The majority element is the element that a... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Maximum XOR of Two Numbers in an Array.py
# Creation Time: 2017/10/11
###########################################
'''
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai <... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Employee Importance.py
# Creation Time: 2018/4/7
###########################################
"""
# Employee info
class Employee(object):
def __init__(self, id, importance, subordinates):... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Perfect Squares.py
# Creation Time: 2017/8/26
###########################################
'''
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4,... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Longest Palindromic Subsequence.py
# Creation Time: 2018/3/17
###########################################
'''
Given a string s, find the longest palindromic subsequence's length in s. You ma... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Implement strStr().py
# Creation Time: 2017/1/21
###########################################
'''
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Number of Atoms.py
# Creation Time: 2018/3/6
###########################################
'''
Given a chemical formula (given as a string), return the count of each atom.
An atomic element a... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Longest Consecutive Sequence.py
# Creation Time: 2017/7/22
###########################################
'''
Given an unsorted array of integers, find the length of the longest consecutive ele... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Reverse Vowels of a String.py
# Creation Time: 2017/9/8
###########################################
'''
Write a function that takes a string as input and reverse only the vowels of a string.... |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Create Maximum Number.py
# Creation Time: 2017/9/2
###########################################
'''
Given two arrays of length m and n with digits 0-9 representing two numbers. Create the ma... |
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: K-diff Pairs in an Array.py
# Creation Time: 2018/4/18
###########################################
'''
defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
... |
class Board:
pieces = {
"O": [(0, 0), (0, -1), (-1, 0), (-1, -1)],
"I": [(-2, 0), (-1, 0), (0, 0), (1, 0)],
"S": [(0, 0), (1, 0), (0, -1), (-1, -1)],
"Z": [(-1, 0), (0, 0), (0, -1), (1, -1)],
"L": [(-1, 0), (-1, -1), (0, 0), (1, 0)],
"J": [(-1, 0), (0, 0), (1, 0), (1,... |
'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
th_count = 0
th_index = word.find("th")
... |
#!python
#cython: language_level=3
import collections
from collections.abc import Iterable
from scipy.sparse import vstack
import numpy as np
import pandas as pd
def quicksort(xs):
if not xs:
return []
return quicksort([x for x in xs if x < xs[0]]) + [x for x in xs if x == xs[0]] + quicksort(
... |
# Import turtle graphics library
import turtle
# Import math functions
from math import *
from random import *
def random_color(turtle):
r, g, b = randint(0, 255), randint(0, 255), randint(0, 255)
turtle.pencolor((r, g, b))
# draw a square centered at the current cursor position
# TODO 1: convert drawSquar... |
# Import turtle graphics library
import turtle
# Import math functions
from math import *
# Function to draw a square about the current position
def drawSquareFromCenter(turtle, x):
turtle.penup()
turtle.forward(-x / 2)
turtle.right(90)
turtle.forward(x / 2)
turtle.left(90)
turtle.pen... |
import json
import io
import argparse
def replaceArray(jsonString):
"""
Replaces json arrays with pseudo arrays for firebaseStr
Example: ["Foo", "Bar"] -> {"0": "Foo", "1": "Bar"}
"""
if jsonString[0] != "[" or jsonString[-1] != "]":
# return None if its not a valid json array
... |
from Tkinter import *
form = Tk()
form.title=("Add New Stock")
Label(form , text="Add new Stock" , font = "Lato 20")
stock_symbol = Label(form , text= "Stock" , font = "Lato 15" , fg = 'White', bg='Black')
stock_symbol.grid(row=0,column=0)
number_of_units = Label(form , text= "Number of stocks" , font = "La... |
import pygame
pygame.init()
(6, 0)
SIZE_HEIGHT = 600
SIZE_WIDTH = 800
screen = pygame.display.set_mode((SIZE_WIDTH,SIZE_HEIGHT))
pygame.display.set_caption('Summative')
clock = pygame.time.Clock()
BLACK = (0,0,0)
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)
#crashed = False
#chance=0
#co... |
# a93323883be13012
import urllib.request
import json
import sqlite3
import ast
from WeatherFunctions import newZipcode
from time import sleep
#-999 = a null value
#A basic conversion of precipitation to snow can be used to obtain an approximate snow reading. If snow precipitation
# is listed as e.g. 0.05 inches, thi... |
text = ("Hey You!") #"Hy Y!" NEED TO REMOVE a, e, i, o, u
vowel = ["a", "e", "i", "o" ,"u", "A", "E", "I", "O", "U"]
def anti_vowel(text):
word = ""
for l in text:
if l not in "aeiouAEIOU":
word += l
return word
print(anti_vowel(text))
|
# Importing libraries
import numpy as np
import pandas as pd # data processing
import datetime # for datetime conversion
from pandas_datareader import data as pdr # for loading Yahoo finance data
def csv_file_operation(df):
# Concatenating Trader Name for convenience
df["Trader_name"] = df["firstName"] + df... |
def quickSort(arr):
#todo: check for single element in array
quickSortHelper(arr,0,len(arr)-1)
def quickSortHelper(arr,first,last):
if first < last:
partitionPosition = partition(arr, first, last)
quickSortHelper(arr,first,partitionPosition-1)
quickSortHelper(arr,partiti... |
def sortInWaveForm(arr):
right = len(arr)-1
for i in range(0,len(arr),2):
if i>0 and arr[i]<arr[i-1]:
arr[i],arr[i-1] = arr[i-1],arr[i]
if i<right and arr[i]<arr[i+1]:
arr[i],arr[i+1] = arr[i+1],arr[i]
print(arr)
#90 10 49 1 5 2 23
arr = [... |
"""
This file contains stack implementation with python list
Stack()
push(item)
pop()
peek()
isEmpty()
size()
displayAllElements()
"""
class MyStack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
... |
class SinglyListNode():
def __init__(self,value):
self.value = value
self.nextnode = None
class LinkedList():
def __init__(self,value):
newNode = SinglyListNode(value)
self.head = newNode
self.tail = newNode
self.size = 1
def appendNode(self,value):
... |
class TwoStacks:
def __init__(self,arraySize):
self.arraySize = arraySize
self.array = [None]*self.arraySize
self.stack1Top = -1
self.stack2Top = self.arraySize
def stack1Push(self,ele):
if self.stack1Top<self.stack2Top-1:
self.stack1Top += 1
... |
"""
約数の数を素数要素の面積のように考える方法
素因数分解を利用して解く解法
ただしN <= 10**10の条件下でTLE
"""
from collections import Counter
N = int(input())
# 素数を求める関数
def factorize(n):
factorys = []
rest_num = n
i = 2
while rest_num > 1:
if rest_num % i == 0:
factorys.append(i)
rest_num //= i
else:
... |
"""
マスターオブ整数
"""
from collections import Counter
N, P = map(int, input().split())
# Pを素因数分解する
if N == 1:
print(P)
exit()
prime_list = []
for i in range(2, int(P**0.5) + 1):
if P % i == 0:
while P % i == 0:
prime_list.append(i)
P //= i
prime_count = Counter(prime_list)
ans... |
"""
マスターオブ整数,素数
約数の総和
"""
"""
約数列挙の回答
"""
N = int(input())
if N == 1:
print("Deficient")
exit()
divisor = []
for i in range(2, int(N**0.5) + 1):
if N % i == 0:
if i != N//i:
divisor.append(i)
divisor.append(N//i)
else:
divisor.append(i)
sum_div = sum(d... |
T = list(input())
for i, s in enumerate(T):
if s == "?":
T[i] = "D"
print("".join(T)) |
# introduction to Classes -
class Student: ## user defined datatype
def __init__(self, name='Python'): # constructor
self.name = name
print("Hello World")
def welcome(self):
print(self.name)
print('Welcome to python programming')
obj = Student('Gurjas')
obj.welcome()
obj1 = Stu... |
# # Lambda - function - Filter, Reduce, Map
list_var = [10, 34, 15, 52, 15, 67, 32, 18]
# without lambda function
# new_list = []
#
# def list_filter(list_var):
# for i in list_var:
# if (i>30):
# # return i
# # print(i)
# new_list.append(i)
#
# list_filter(list_var)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.