text stringlengths 5 121k |
|---|
from urllib.request import *
from urllib.parse import *
import json
import sqlite3
apiKey = "a808bbf30202728efca23e099a4eecc7"
city = input("Enter the name of a city whose weather you want: ")
params = {"q":city, "units":"imperial", "APPID":apiKey }
arguments = urlencode(params)
address = "http://api.open... |
lis=[1,2,4,10,45,8]
lis.sort()
print("largest no. is",lis[-1])
|
import sys
import logging
from doc import *
if '-v' in sys.argv:
print('Phone number Wordlist Generator v.' + VERSION)
exit()
elif '-h' in sys.argv:
print(HELP)
exit()
logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.INFO)
def main(suffix):
global digits_number
dig... |
demo_tuple_drinks = ("coffee", "tea", "water")
demo_tuple_foods = ("bread", "steak", "fish")
print("The contents in the tuple: ", demo_tuple_drinks)
print("The length of the tuple: ", len(demo_tuple_drinks))
print("The Tuple types: ", type(demo_tuple_drinks))
nested_tuple = tuple((demo_tuple_drinks))
print(nested_tu... |
class CA:
num = 101
def __init__(self):
self.a = 102
def show(self):
print("num is: ", self.num)
print("num is: ", CA.num)
cRef = CA()
cRef.show()
|
import time
def timeit(func):
def wrap_func(*args, **kwargs):
t1 = time.time()
result = func(*args, **kwargs)
t2 = time.time()
print(f'Function {func.__name__!r} executed in {(t2-t1):.4f}s')
return result
return wrap_func |
import sqlite3
def create_tables(db_file):
conn = sqlite3.connect(db_file)
c = conn.cursor()
c.execute (''' DROP TABLE IF EXISTS user''')
c.execute (''' CREATE TABLE user
(user_name text PRIMARY KEY,
user_pass text NOT NULL,
ful... |
print(5+4)
print(4.5+ 5)
num1 =input()
num2= input()
print(int(num1)+int(num2))
i=100
j=200
x=300
y=100
print((i == j) or (i == x))
print((i<j) and (i>=y))
print((i!=j) and (i != x))
print((i<j) and (i<x) and (i<y))
|
import turtle as j
def main () :
j.setup(width=800 , height=800)
j.title("Turtle Project - turtleIntro")
j.bgcolor("#1de047")
line ()
square ()
circle ()
triangle ()
j.exitonclick ()
def line () :
j.pencolor('green')
moveT(50 , 0)
j.left(180)
j.forward(100)
d... |
from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371
return c... |
def get_matrix(key):
'''takes a key and returns
matrix: a 5x5 matrix of letters
locations: a dictionary with letters as keys and (row, column) as value
'''
letters = 'abcdefghijklmnopqrstuvwxyz'
matrix_text = key + letters
matrix_text = matrix_text.lower()
matrix_text = matrix_text.repla... |
class Calculator:
def __init__(self, choice, num1, num2):
self.choice = choice
self.num1 = num1
self.num2 = num2
self.__total = None
def switcher(self):
choice_dict = {
'1': 'add',
'2': 'sub',
'3': 'mult',
'4': 'div',
... |
for i in range(10, 100):
num1 = i // 10
num2 = i % 10
num_sum = num1 + num2
if(num_sum**2 == i):
print(i)
for i in range(100):
divisor_count = 0
for j in range(1, i+1):
if(i % j == 0):
divisor_count += 1
if(divisor_count == 10):... |
import random
import datetime
class KitchenDutyPlanner(object):
def __init__(self):
self.date = datetime.datetime(2017, 4, 1)
self.end_date = datetime.datetime(2017, 5, 1)
self.day = datetime.timedelta(days=1)
self.online_marketing_team = [
"Max Wölfle",
... |
"""
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入:n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
"""
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
if n < 1:
return ... |
class Solution(object):
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
if not IP:
return "Neither"
if IP.count(":") == 7:
return self.valid_IPv6(IP)
elif IP.count(".") == 3:
return self.valid_IPv4(IP)
... |
"""
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
"""
class Solution(object):
def convertToTitle(sel... |
class Solution(object):
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
hashmap = [0] * 128
count = 0
for char in s:
hashmap[ord(char) - ord("A")] += 1
if hashmap[ord(char) - ord("A")] % 2 =... |
class Solution(object):
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
stack = [(0, 0)]
self.seen = set()
while stack:
remain_x, remain_y = stack.pop()
if remain_x == z ... |
"""
请设计一个类,使该类的构造函数能够接收一个单词列表。然后再实现一个方法,该方法能够分别接收两个单词 word1 和 word2,并返回列表中这两个单词之间的最短距离。您的方法将被以不同的参数调用 多次。
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"]
输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = "makes", word2 = "coding"
输出: 1
注意:
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。
""... |
"""
给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。
示例 1:
输入: "acba"
输出: True
ab (1) cd (c) ba
"""
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l = 0
r = len(s) - 1
while l < r:
if s[l] != s[r]:
... |
"""
给出一个区间的集合,请合并所有重叠的区间。
示例 1:
输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]
"""
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if not intervals or len(... |
"""
Return the index of the first occurrence of needle in haystack,
or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
"""
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype... |
"""
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假如说有多个众数,则要把他们都求出来
"""
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.count = 1
self.max = 0
self.pre = None
self.res = []
self.he... |
"""
Given a n x n matrix where each of the rows and columns are sorted in ascending order,
find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
"... |
"""
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
给一个binary数组,找出最长的子数组,0,1数量相等
链接:https://www.jianshu.com/p/7108226dc023
"""
class Solution(object):
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
... |
"""
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
"""
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target not in nums... |
"""
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
注意:这题题目给的intervals是排序好的
"""
class S... |
"""
You have a number of envelopes with widths and heights given as a pair of integers (w, h).
One envelope can fit into another if and only if both the width and height of one envelope is
greater(严格大于哦) than the width and height of the other envelope.
What is the maximum number of envelopes can you Russian doll? (put... |
"""
给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。
word1 和 word2 是有可能相同的,并且它们将分别表示为列表中两个独立的单词。
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"].
输入: word1 = “makes”, word2 = “coding”
输出: 1
输入: word1 = "makes", word2 = "makes"
输出: 3
"""
import sys
class Solution(object):
def shortestWordDistance... |
def mergesort(data):
if len(data) == 1:
return data
middle = len(data) // 2
left = mergesort(data[:middle])
right = mergesort(data[middle:])
return merge(left, right)
def merge(left, right):
l = 0
r = 0
result = []
while l <= len(left) - 1 and r <= len(right) - 1:
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def pre(node):
if node == None:
return
print(node.val)
pre(node.left)
pre(node.right)
def preOrder(root):
if root == None:
re... |
"""
Design a class to find the kth largest element in a stream.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call t... |
"""
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
"""
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return []
self.res = []
nums.... |
"""
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例 1:
输入: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
输出: true
"""
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
... |
import sys
def calc(val1, val2, op):
if op == '+':
return val1 + val2
elif op == '-':
return val1 - val2
elif op == '*':
return val1 * val2
def unwind(operators, operands):
while len(operands) > 0 and len(operators) > 0:
valr = int(operands.pop())
vall = i... |
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head:
return head
dummy = ListNode(float("-inf"))
curr = head
while curr:
next = curr.next
prev2 = dummy
curr2 = dummy.next
while ... |
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
from collections import deque
class Solution:
def connect(self, root... |
from collections import deque
class Solution:
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
s1 = deque(sentence1.split())
s2 = deque(sentence2.split())
while s1 and s2 and s1[0] == s2[0]:
s1.popleft()
s2.popleft()
... |
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
min_depth = 1
row = [root]
while row:
next_row = []
for node in row:
if not (node.left or node.right):
return min_de... |
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
stack = []
head = TreeNode(None)
right = head
curr = root
while True:
while curr.left:
stack.append(curr)
curr = curr.left
stack[-1].left = N... |
from queue import PriorityQueue
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
if not trips:
return True
q = PriorityQueue()
for num_passengers, start_location, end_location in trips:
q.put((start_location, num_passenge... |
import argparse
parser = argparse.ArgumentParser(description = 'Simply program , reverse text')
parser.add_argument('-n', help='file name', type=str)
parser.add_argument('-l', help = 'line number', type=int)
parser.add_argument('-v', help = 'file version', type=str)
args = parser.parse_args()
lines = []
try:
... |
from collections import OrderedDict
def partition(iterable,*conditions):
'''Returns a list with the elements that satisfy each of condition.
Conditions are assumed to be exclusive'''
d= OrderedDict((i,list())for i in range(len(conditions)))
for e in iterable:
for i,condition in enume... |
import random
import math
from dtnsim.mobility.rwp import RandomWaypoint
from dtnsim.vector import Vector as V
def pareto(scale, shape):
"""Generate a random variable following the Pareto distribution with
parameters SCALE and SHAPE. Note that the mean of the Pareto distribution
is gi... |
""" Contains the car class and its relevant functionality """
class Car:
""" Contains all the attributes for a Car """
def __init__(self, car_id: str, driver_age: int):
""" Initializes a new car object """
self.car_id = car_id
self.driver_age = driver_age
self.slot = None
... |
'''
Created on 2020-08-06 14:28
@author: chengbo
- 05 递归
问题:编程实现斐波那契数列求值f(n)=f(n-1)+f(n-2)
问题:编程实现求阶乘n!
问题:编程实现一组数据集合的全排列
'''
def fibonacci(n):
assert n >= 1
if n < 3:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
def factorial(... |
def fib():
"""
:return: 0, 1, 1, 2, 3, 5, 8, 13, 21 ...
"""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
x = fib()
print(next(x))
print(next(x))
print(next(x)) |
import sys
def get_numbers():
start = 0
end = 10
step = 1
while start < end:
yield start
start += step
gen = get_numbers()
print(next(gen))
print(next(gen))
print(list(gen))
try:
gen = get_numbers()
for i in gen:
print(i)
except StopIteration as e:
print(e) |
def error(value=None):
x = None
import random
if value == None:
x = random.randint(1, 3)
try:
if x == 1:
raise ValueError
elif x == 2:
raise TypeError
elif x == 3:
raise RuntimeError
else:
1 /int(value)
except ValueError:
print('123')
except TypeError:
print('321')
except RuntimeError:
... |
while True:
x, y = float(input('x= ')), float(input('y= '))
sign = input('Знак операции (+, -, /, *): ')
if sign in ('+', '-', '/', '*'):
if sign == '+':
print(x+y)
elif sign == '-0:':
print(x-y)
elif sign == '*':
print(x*y)
elif sign == '/... |
from sklearn import tree
model = tree.DecisionTreeClassifier(criterion='gini')
model.fit(X, y)
model.score(X, y)
predicted= model.predict(x_test)
|
def encryptor(key, message):
def encode(l):
return chr(ord('A' if l.isupper() else 'a') + (ord(l) - ord('A' if l.isupper() else 'a') + key) % 26)
return ''.join(encode(l) if l.isalpha() else l for l in message)
|
import numpy as np
def validSolution(board):
board = np.array(board)
for i in range(9):
if len(set(board[i, :])) != 9 or len(set(board[:, i])) != 9:
return False
for i in range(3):
for j in range(3):
if len(set(board[i * 3:(i + 1) * 3, j * 3:(j + 1) * 3].flatten(... |
class CaesarCipher(object):
def __init__(self, shift):
self.shift = shift
def cipher(self, text, mode):
return ''.join(chr(ord('A') + (ord(l.upper()) - ord('A') + self.shift * (1 if mode else -1)) % 26) if l.isalpha() else l for l in text)
def encode(self, text):
return se... |
def triple_double(num1, num2):
return any(chr(c) * 3 in str(num1) and chr(c) * 2 in str(num2) for c in range(ord('0'), ord('9') + 1)) |
def areYouPlayingBanjo(name):
return name + (' plays banjo' if name[0].lower() == 'r' else ' does not play banjo')
|
import collections
def find_shortest_path(grid, start_node, end_node):
if not (grid and start_node and end_node):
return []
stack = collections.deque([start_node])
moves = [(0, 1), (1, 0), (0, -1), (-1, 0)]
visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
visit... |
class T:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def is_bst(node):
def is_bst_asc(node, min=None, max=None):
return node is None or (min is None or node.value > min) and (max is None or node.value < max) \
... |
def nickname_generator(name):
return name[:3 + (name[2].lower() in 'aioue')] if len(name) > 3 else 'Error: Name too short' |
import itertools
def find_longest_substr(s):
start = 0
char = None
length = 0
current_index = 0
for k, g in itertools.groupby(s):
g = list(g)
if g[0] not in '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' and len(g) > length:
start = current_index
length = len(g)
... |
from math import sqrt
def sum_of_squares(n):
n_sqrt = int(sqrt(n))
if n == n_sqrt * n_sqrt:
return 1
div, mod = divmod(n, 4)
while mod == 0:
div, mod = divmod(div, 4)
if (div * 4 + mod) % 8 == 7:
return 4
for i in range(1, n_sqrt + 1):
temp = n - i * i
... |
from collections import Counter
def find_uniq(arr):
return next(k for k, v in Counter(arr).items() if v == 1) |
import re
def title_case(title, minor_words=''):
minor_words = set(map(str.lower, minor_words.split()))
def repl(m):
if m.start() == 0 or m.group().lower() not in minor_words:
return m.group().title()
else:
return m.group().lower()
return re.sub('[a-z]... |
class Node():
def __init__(self, data, next = None):
self.data = data
self.next = next
def iter_linked_list(current):
while current is not None:
yield current.data
current = current.next
yield None
def stringify(list):
return ' -> '.join(str(x) for x in iter_linked_l... |
def powers_of_two(n):
return [2 ** x for x in range(n + 1)] |
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class Context(object):
def __init__(self, source, dest):
self.source = source
self.dest = dest
def move_node(source, dest):
if source is None:
raise ValueError()
... |
n=int(raw_input())
v="no"
for i in range(n+1):
r=2**i
if(n==r):
v="yes"
print(v)
|
import sys
sys.path.append("../linkedList")
from LinkedQueue import LinkedQueue
def merge(S1, S2, S):
"""
Merge two sorted queue instances S1 and S2 into empty queue S.
:param S1:
:param S2:
:param S:
:return:
"""
while not S1.is_empty() and not S... |
def binary_search(data, target, low, high):
'''
Return True if target is found in indicated potion of a Python list
:param data:
:param target:
:param low:
:param high:
:return:
'''
if low > high:
return False
else:
mid = (low + high) // 2
if data[mid] ... |
num = int(input())
num2 = int(input())
prod = num*num2
print(f'PROD = {prod}') |
'''字典树'''
class Trie():
def __init__(self):
self.root = {}
def insert(self, x):
p = self.root
i = 0
while i < len(x) - 1:
if x[i] not in p.keys() and x[i] + '!' not in p.keys():
p[x[i]] = {}
if x[i] in p.keys():
p... |
__author__ = "niels kjer"
class BinarySearchST(object):
def __init__(self, k=[], v=[], n=0):
self.keys = k
self.values = v
self.n = n
def is_empty(self):
return self.n == 0
def size(self):
return self.n
def get(self, key):
if self.is_empty(): ... |
def sort(arr):
merge_sort_bottom_up(arr)
def merge_sort_bottom_up(arr):
n = len(arr)
length = 1
while length < n:
lo = 0
while lo < n-length:
merge(arr, lo, lo+length-1, min(lo+length+length-1, n-1))
lo += length + i
length *= 2
def merge_sort_to... |
def calculate_sqr(n):
"""
Calculate squre of a positive integer recursively using
n^2 = (n-1)^2 + 2(n-1)+ 1 formula
"""
if n == 1:
return 1
else:
return calculate_sqr(n - 1) + 2 * (n - 1) + 1
|
from classes.guest import Guest
from classes.song import Song
class Room:
def __init__(self, input_room_name, input_room_price, input_room_capacity):
self.name = input_room_name
self.price = input_room_price
self.capacity = input_room_capacity
self.till = []
self.guests = ... |
num = int(input("Enter your age: "))
if num >= 0 and num <=34:
print("Young")
elif num >= 35 and num <= 50:
print("Mature")
elif num >= 51 and num <= 69:
print("Middle-aged")
elif num >= 70:
print("Old")
else:
print("Invalid age") |
d1 = int(input("Input first dice: "))
d2 = int(input("Input second dice: "))
sum_d = d1 + d2
if (d1 <= 0 or d1 > 6) or (d2 <= 0 or d2 > 6):
print("Invalid input")
elif sum_d == 7 or sum_d == 11:
print("Winner")
elif sum_d == 2 or sum_d == 3 or sum_d == 12:
print("Loser")
else:
print(d1 + d2)
... |
inches_str = input("How many inches of rain have fallen: ")
inches_int = int(inches_str)
volume = (inches_int/12)*43560
gallons = volume * 7,48051945
print(inches_int," inches of rain on 1 acre is", gallons, "gallons")
|
Apple = float(input("Enter apple quantity: "))
Orange = float(input("Enter orange quantity: "))
AppleCost= 20.00* Apple
OrangeCost= 25.00* Orange
TotalAmount= AppleCost + OrangeCost
format_TotalAmount= "{: .2f}".format(TotalAmount)
float_TotalAmount = float(format_TotalAmount)
print("Total Amount is: ", format_TotalAm... |
"""
Description: This file allows the server and client to connect with each other and
send/receive data on the game.
"""
import socket
import pickle
class Network():
def __init__(self, serverIP):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = serverIP... |
nums = [1,1,2,1,3,4,3,4,5,5,6,7,8,7,9,9]
names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']
nums = [1,2,3,4,5,6,7,8,9,10]
import datetime
my_date = datetime... |
from tkinter import *
window = Tk()
window.title('Text Files')
window.geometry("500x400")
window.configure(background="pink")
heading=Label(text="My weekend activities" , bg = "light grey" , fg="black")
heading.pack()
def create():
file=open('/home/user/Desktop/my_weekend_activities.txt','w+')
file.write("My w... |
char = input("entre un mot:")
n = int(input("entre un nombre:"))
miss_char = char[0:n]+char[n+1:]
print(miss_char) |
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.corpus import brown
totalTokens = 0
example_test = "Hello Mr. Smith, how are you doing today? The weather is great and Python is awesome. The sky is pink, and you should not go outside."
val = input("Choose ... |
def determinemode():
numlist = []
freqlist = []
print("Hello! I will calculate the longest sequence of numbers in a list.")
print("Type your list of numbers and then type \"end\".")
num = (input("Please enter a number: "))
def CheckNum(num):
try:
num = int(num... |
from sys import argv
print("Inside com line arg sum.py program")
count=0
y=0
for x in argv:
if x=='com line arg sum.py':
continue
y=y+int(x)
count+=1
print("Total no of argument is {} and the sum of argument is {}".format(count,y))
|
from flask import Flask, render_template, redirect, url_for, request
data = {}
app=Flask(__name__,template_folder="templates")
@app.route('/')
def intro():
return render_template('intro.html')
@app.route('/register.html')
def register():
return render_template('register.html')
@app.route('/login.html')
def log... |
from tkinter import *
window = Tk()
window.geometry("500x500")
text = StringVar()
window_message = Message(window, textvariable = text)
text.set("HELLO WORLD")
window_message.config(width=500, pady=250, font=("Consolas", 60),
bg = 'light blue')
window_message.pack()
... |
""" str() is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable.
if __repr__ is defined, and __str__ is not, the object will behave as though __str__=__repr__.
This means, in simple terms: almost every objec... |
message = "The price of the stock is:"
price = "$1110"
print(id(message))
message = message + " " +price
print(id(message))
name = "interstella"
print(name[0])
print(name[0:5])
nums ="0123456789"
print(nums[2:6])
print(nums[0:6:2])
print(nums[::2])
print(nums[::-1]) |
class Student:
def __init__(self, first, last, courses=None ):
self.first_name = first
self.last_name = last
if courses == None:
self.courses = []
else:
self.courses = courses
pass
courses_1 = ['python', 'go', 'javascript']
course... |
'''
- In application you will have to load data from persistent memory to working memory as objects.
- Once loaded, you can work with data in these objects and perform operations as necessary
Exmaple)
1. In Database or other data source
2. Load data
3. Save it in data structure like `Dictionary`
4. Get the data from... |
print('Hello World using single quotes')
print("Hello World using double quotes")
''' print("""Hello world using
triple quotes, also known as
multi-line strings""") '''
print("Hello world I'm using single quotes")
print('Hello world "using quotes here" double quotes')
print('Hello World I\'m using single quotes')
p... |
import time
class Node:
def __init__(self, data = None):
''' Initialize node with data and next pointer '''
self.data = data
self.next = None
class Stack:
def __init__(self):
''' Initialize stack with stack pointer '''
print("Stack created")
self... |
def bisection_recur(n, arr, start, stop):
if start > stop:
return (f"{n} not found in list")
else:
mid = (start + stop) // 2
if n == arr[mid]:
return (f"{n} found at index: {mid}")
elif n > arr[mid]:
start = mid + 1
return bisection_recu... |
pronouns = ["io", "tu", "lei", "lui", "Lei", "noi", "voi", "loro"]
imperfect_endings = ["vo", "vi","va","vamo","vate","vano"]
essere = {
"indicative":["sono","sai","e","e","e", "siamo", "siete","sono"],
"past participle": ("derp" for x in xrange(len(pronouns))),
"imperfect" : ["ero","eri","era","era","era", "erava... |
name = input('Введите имя: ')
name1 = name.lower()
name2 = name[::-1]
name2 = name2.lower()
def cheking_name (name_revers):
if name1 == name2:
print("True")
else:
print('False')
cheking_name(name) |
shares, likes = 5, 2
for _ in range(int(input())-1):
shares = (shares // 2) * 3
likes += shares // 2
print(likes)
|
'''
Digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n.
If that value has more than one digit, continue reducing in this way until a single-digit number is produced.
This is only applicable to the natural numbers.
'''
import unittest
def digitalRoot(n:int):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.