text stringlengths 37 1.41M |
|---|
def word_count(str):
counts = dict()
word = str,split('')
for word in words:
if word in counts:
counts[word] =+ 1
else:
return count
word_count('the quick brown fox jumps over the lazy dog.')
|
#Level1
def lesser_of_two_evens(a, b):
if a % 2 == 0 and b % 2 == 0:
if a > b:
print('both numbers are even and lesser is' + str(b))
else :
print('both numbers are even and lesser is' + str(a))
else:
if a > b:
print('both numbers are odd and' ... |
__author__ = 'Tamby Kaghdo'
#My solution to the Kata: Excel's COUNTIF, SUMIF and AVERAGEIF functions
def to_num(s):
try:
return int(s)
except ValueError:
return float(s)
def count_if(values,criteria):
ops = [">","<","<=",">=","<>"]
counter = 0
condition_part = ""
value_part = ... |
## 2. Condensing class size ##
class_size = data["class_size"]
#only high school
class_size = class_size[class_size["GRADE "] == "09-12"]
#only GEN ED
class_size = class_size[class_size["PROGRAM TYPE"] == "GEN ED"]
print(class_size.head(5))
## 3. Computing average class sizes ##
import numpy
class_size = class_size.... |
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def multiple_sum_finder(max):
y = 0
for x in range(0,max):
if x % 3 == 0:
y += x
elif x % 5 =... |
# O(N) Time | O(N) Space
def caesarCipherEncryptor(string, key):
newLetters = []
newKey = key % 26
for letter in string:
newLetters.append(getLetter(letter, newKey))
return "".join(newLetters)
def getLetter(letter, key):
newLetterCode = ord(letter) + key
return chr(newLetterCode) if ne... |
totalseconds = int(input('Input the number of seconds:'))
days = totalseconds//86400
hours = (totalseconds%86400)//3600
minutes = (totalseconds%3600)//60
seconds = totalseconds%60
print(days,':',hours,':',minutes,':',seconds,sep='') |
class Node:
data = None
next = None
def __init__(self, data):
self.data = data
def append(self, data):
node = self
while node.next is not None:
node = node.next
node.next = Node(data)
class Stack:
top = None
def push(self, item):
node = No... |
from base import Node, print_nodes
def find_nth_to_last(root, nth):
if root is None or nth < 0:
return None
p2 = root
for x in xrange(0, nth):
p2 = p2.next
if p2 is None:
return None
p1 = root
while p2.next is not None:
p1 = p1.next
p2 = p2.next
... |
def rotate90(matrix, n):
for layer in xrange(0, n / 2):
first = layer
last = n - 1 - layer
for i in xrange(first, last):
offset = i - first
top = matrix[first][i]
matrix[first][i] = matrix[last - offset][first]
matrix[last - offset][first] = ma... |
class Node:
left = None
right = None
value = None
def __init__(self, value):
self.value = value
class Tree:
root = None
def insert_new(self, node, value):
if node.value > value:
if node.left:
return self.insert_new(node.left, value)
els... |
# Playing Around with what i learned on day 1
# When doing day 1 I thought back on when I was learning alittle about f strings & And playing with lists
# Played around with it abit here in my creativity.
# Storing characters into a list[] & Some words into a string.
Southpark_Characters = "Stan", "Cartmen", "Ke... |
print("Hello World!")
print("Hello('World')")
print("Hello " + "\nWorld")
# Debug Exercise
print("Day 1 - String Manipulation")
print("String Concatention is done with the '+' sign.")
print("e.g print('Hello World!')")
print("New lines can be added with a backslash n.")
# Input Function Exercise.
name = in... |
"""Useful things to do with dates"""
import datetime
def date_from_string(string, format_string=None):
"""Runs through a few common string formats for datetimes,
and attempts to coerce them into a datetime. Alternatively,
format_string can provide either a single string to attempt
or an iterable of st... |
#Haemi Lee
#Version 2
#Fall 2018
#Holds Turtle Interpreter class
import turtle
import random
import sys
class TurtleInterpreter:
def __init__(self, dx = 800, dy = 800):
turtle.setup(width = dx, height = dy )
turtle.tracer(False)
def drawString(self, dstring, distance, angle):
""" Interpret the characte... |
# import sqlite3
# from_conn = sqlite3.connect("words.db")
# to_conn = sqlite3.connect("db.sqlite3")
# from_cur = from_conn.cursor()
# to_cur = to_conn.cursor()
# print(from_conn.execute("select name from sqlite_master where type='table';").fetchall())
# words > 'dictionary_words
# print(to_conn.execute("select name... |
import pandas as pd
from datetime import date
import psycopg2
import config
def populate_user_table_from_csv(csv_file):
conn = psycopg2.connect(
host=config.live_config.host,
database=config.live_config.database,
user=config.live_config.user,
password=config.live_co... |
class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
class PessoaFisica(Pessoa):
def __init__(self, nome, idade, cpf):
Pessoa.__init__(self,nome,idade)
self.cpf = cpf
def __repr__(self):
return f'{self.nome} tem {self.idade} ano(s), e... |
from keras import layers
from keras import models
'''have 32 filters using a 5×5 window for the convolutional layer and a 2×2 window for the pooling
We will use the ReLU activation function.
In this case, we are configuring a convolutional neural network to process an input tensor of
size (28, 28, 1),which is the... |
## """A dict of dict will have connected nodes details in dict with weight """
g = {
"n1" : {"n2": 5, "n3": 6},
"n2" : { "n1": 2 , "n4": 9 },
"n3" : {"n1" : 6, "n4" : 3},
"n4" : {"n1" : 3, "n2" : 5, "n3" : 8}
}
if __name__ == '__main__':
print(repr(g))
|
class LinkedListNode(object):
def __init__(self,index, data):
self.index = index
self.data = data
self.next = None
class AdjNode(LinkedListNode):
pass
# A class to represent a graph. A graph
# is the list of the adjacency lists.
# Size of the array will be the no. of the
# vertices ... |
class Fraction(object) :
def __init__(self,num,den):
self.num = num
self.den = abs(den)
def show(self):
print(str(self.num) + "/" + str(self.den) )
def __str__(self):
return(str(self.num) + "/" + str(self.den))
def __add__(self,other_fraction):
new_num = (self.nu... |
class Node(object):
def __init__(self,id):
self.connected_to = {}
self.id = id
def add_neighbour(self,nbr, weight):
self.connected_to[nbr] = weight
###Considering graph as dicitionary
class Graph(object):
def __init__(self):
self.vertices = {}
self.number_of_nodes =... |
#--------Abstract classes -------
class Shape2DInterface:
def draw(self):
pass
class Shape3DInterface:
def build(self):
pass
#-------- Concrete classes -------
class Circle(Shape2DInterface):
def draw(self):
print("Circle.draw")
class Square(Shape2DInterface):
def draw(self):... |
'''
list 타입을 선언하고 list에 엘리먼트 추가, 삭제
'''
'''
num_list = [10, 20, 30, 40, 50, 60]
print(type(num_list),num_list)
print(num_list[0], num_list[0:3], num_list[3:])
for idx, num in enumerate(num_list):
print(idx, num)
str_list = ['python', 'java', 'kotlin', 'C++', 'Scalar']
str_list[1] = 'java script'
print(str_list[1]... |
def fah_convert(value):
fehren = (9 * value) / 5 + 32
return fehren
celcius = float(input("변환하고 싶은 섭씨온도를 입력해주세요 : "))
fehren = fah_convert(celcius)
print("섭씨온도 :",celcius)
print("화씨온도 :",round(fehren,2))
|
# trzeba zainstalowac matplotlib
# https://matplotlib.org/users/installing.html
# easy
# python -m pip install -U pip
# python -m pip install -U matplotlib
import matplotlib.pyplot as plt
def next_vertex(x, y):
h = (x**2 + y**2)**0.5
return (x - y / h, y + x / h)
plt.axes().set_aspect(1)
plt.axis('off')
#... |
lista = []
liczba = int(input("Podaj liczbe elementow: "))
for x in range(0, liczba, 1):
lista.append(int(input()))
print("Twoje liczby to :", lista)
print("--------------------")
print("Najwieksza to: ", max(lista))
|
print('Witaj! To jest moj program *yey*, zapraszam.')
#brakowalo ponizej nawiasu na koncu
#p=int(input('podaj liczbe powtorzen ')
p=int(input('podaj liczbe powtorzen '))
ilosc = 0
while p > 0:
p -= 1
ilosc += 1
print('|-|')
|
import math
print(3 + 2)
print(3 -2)
print(3/2)
print(3%2)
a = 10
a = a+a
print(a)
z = 0.1+0.2-0.3
print(math.floor(z))
|
import time
def countdown(t):
seconds = t * 60
while seconds:
mins,secs = divmod(seconds,60)
timer = f"{mins:02d}:{secs:02d}"
print (timer,end = '\r')
time.sleep(1)
seconds-=1
print ("time up bye bye")
t = input ("enter time in minutes ")
countdown(int(t)) |
from socket import *
serverName = "localhost"
serverPort = 5006
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
def main():
user_main_menu()
choice = make_choice_in_menu()
if choice == 0:
clientSocket.send(str(choice).encode())
print("You left ... |
'''
单元测试unittest
'''
import unittest
# 必须继承TestCase类
class Test01(unittest.TestCase):
@classmethod # 注解
def setUpClass(self):
print('*******这是setUpClass方法*******')
@classmethod
def tearDownClass(self):
print('*******这是tearDownClass方法*******')
# 继承自父类TestCase的方法,名字不能乱写
# set... |
import collections
import pdb
class TrieNode():
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.word_count = 0
class Solution(object):
def build_trie(self, words):
self.root = TrieNode()
for word in words:
node = self.root
for w... |
__author__ = 'ChiYuan'
#
# Given a list of numbers, L, find a number, x, that
# minimizes the sum of the absolute value of the difference
# between each element in L and x: SUM_{i=0}^{n-1} |L[i] - x|
#
# Your code should run in Theta(n) time
#
from random import randint
def minimize_absolute(L):
global cl... |
"""
286. Walls and Gates
https://leetcode.com/problems/walls-and-gates/
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a... |
"""
443. String Compression
DescriptionHintsSubmissionsDiscussSolution
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the ... |
"""
207. Course Schedule
https://leetcode.com/problems/course-schedule/
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total numb... |
# Given a linked list, swap every two adjacent nodes and return its head.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
... |
"""
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
"""
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n==0:return 0
node_range = range(1,n+1)
self.dict_num_tree = {}
retur... |
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
first_zero_pos = -1
last_zero_pos = -1
for i in range(len(nums)):
if nums[i] ==0 and first_zero_po... |
import math
class Point(object):
"""Point class stores and X,Y pair in meters"""
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
#returns the pythagorean distance between two points
def distTo(self, other):
return math.sqrt((self.x-other.x)**2 + (self.y-other.y)**2)
#returns the global bearing o... |
def adadaval(n):
k = 1
count = 0
while k <= n:
if n % k == 0:
count += 1
k += 1
if count == 2:
return True
else:
return False
n = int(input('enter a number:'))
k = 1
while k <= n:
if adadaval(k):
print(k)
k += 2
|
def area(r):
return r * r
def environment(r):
return 4* r
r = int(input("megdar zele morabe ra vared knid:"))
print("masahat:", + area(r))
print("mohit:", +environment(r))
|
list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
list2 = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
# for i in range(len(list1)):
# for j in range(len(list2)):
# list1[i]==list2[j]
list3 = zip(list1,list2)
list4=list(list3)
list4.sort(key = lambda x: x[1])
print(list4) |
# -*- coding: UTF-8 -*-
# 获取今天、昨天和明天的日期
# 引入datetime模块
def testdatetime():
from datetime import datetime
# 计算今天的时间
today = datetime.date.today()
# 计算昨天的时间
yesterday = today - datetime.timedelta(days=1)
# 计算明天的时间
tomorrow = today + datetime.timedelta(days=1)
# 打印这三个时间
... |
#citire date de la tastatura1
produs_dorit = str(input("Care este produsul pentru care verificati stocul? "))
bonuri = int(input("Cate cititi?: "))
#definire matrice
date = {}
date["bonuri"] = {}
date["produse_bon"] = {}
date["stoc"] = {}
for bon in range(bonuri):
bon += 1
date["bonuri"][bon] = {}
produse... |
# PYTHON: Reverse-sort the lines from standard input
# execute:python rosetta.py < testcase.list> testcase.out
import sys # bring in s standard library
lines = sys.__stdin__.readlines() # read every line from stdin into an array
# 假设输入的就是有向无环图
# lines.sort(reverse = True)
# 新建一个数组,每一个元素都是不同的
# 再建一个字典,key为每个不同的... |
import random
bienvenida = input(
'\n- Hola, a continuacion tenes que adivinar el nro entre uno y cien que piense yo. \nPresiona ENTER para comenzar..')
nro = random.randint(1, 2)
intentos = 0
nroIngresado = int(input('- ingresa el numero \n\t'))
while nroIngresado != nro:
intentos += 1
print('- ya llevas', inten... |
# 使用点语法获取json数据
from collections import abc
class Solution(object):
def __init__(self, mapping):
self._data = dict(mapping)
def __getattr__(self, name):
if hasattr(self._data, name):
return getattr(self._data, name)
else:
return Solution.build(self._data[name])
... |
import pandas as pd
import plotly.express as px
df = pd.read_csv('./csv files/data.csv')
#fig = px.line(df, x='Year', y='Per capita income', color='Country', title='Per Capita Income')
#fig = px.bar(df, x='Country', y='InternetUsers')
fig = px.scatter(df, x='Population', y='Per capita')
fig.show()
|
''' an attempt to randomly generate text
'''
from tkinter import *
from random import randint, sample, choice
class RandomCharsGen:
def __init__(self):
self.root = Tk()
w, h = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
self.root.overrideredirect(1) # go in full screen mode
self.... |
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s " % (from_file, to_file)
#in_file = open(from_file)
# method 1, file.read(name of file)
#in_data = file.read(in_file)
# method 2, var_name = in_file(type file).read()
#in_data = in_file.read()... |
class Component: #union find, dfs
"""
323. Number of Connected Components in an Undirected Graph
https://www.lintcode.com/problem/graph-valid-tree/description
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components ... |
#dfs需要深度参数,深度参数可以隐藏在其他参数里,ex: len
"""
17. Subsets
https://www.lintcode.com/problem/subsets/my-submissions
Given a set of distinct integers, return all possible subsets.
"""
def subsets(self, a):
ans = []
self.dfs(sorted(a), [], ans, 0)
return ans
def dfs(self, a, p, ans, i):
if ... |
"""
41. First Missing Positive
https://leetcode.com/problems/first-missing-positive/
Given an unsorted integer array nums, find the smallest missing positive integer.
Follow up: Could you implement an algorithm that runs in O(n) time and uses constant extra space.?
Example 1: Input: nums = [1,2,0] Output: 3
Example 2: ... |
class array:
"""
686. Repeated String Match
Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b to be a substring of a after repeating it, return -1.
Notice: string "abc" repeated 0 times is "", repeated 1 time ... |
"""
128. Longest Consecutive Sequence
https://leetcode.com/problems/longest-consecutive-sequence/
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
Follow up: Could you implement the O(n) solution?
Example 1: Input: nums = [100,4,200,1,3,2] Output: 4
Explanation: ... |
class Heterodromous:
"""
56. Two Sum
https://www.lintcode.com/problem/two-sum/description
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target,
where index1 must be less than index... |
# 1 kilometer is equal to 0.62137 miles.
#Miles = kilometer * 0.62137
#Kilometer = Miles / 0.62137
km=float(input('Enter the kilometers?:'))
print("To miles it is :", (km*0.62137)) |
l = int(input())
r = int(input())
list=[]
for i in range(l,r+1):
for j in range(i,r+1):
x=i^j
list.append(x)
print(max(list))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
np=input().split()
n=int(np[0])
p=int(np[1])
l1=[]
for i in range(p):
l=list(map(float,input().split()))
l1.append(l)
for i in zip(*l1):
a=sum(i)/len(i)
print(a)
|
def spiral_alphabet_print(m,n,a):
k=0
l=0
while(k<m and l<n):
for i in range(l,n):
print(a[k][i],end=" ")
k+=1
for i in range(k,m):
print(a[i][n-1],end=" ")
n-=1
if(k<m):
for i in range(n - 1, (l - 1), -1):
... |
num1 = input('Enter first number:')
num2 = input('Enter second number:')
print("sum is :",int(num1)+int(num2))
print("multiplication is :",int(num1)*int(num2))
print("division is :",float(num1)/float(num2))
print("mod is :",float(num1)%float(num2))
|
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
count=0
if len(flowerbed)==1 and flowerbed[0]==0:
return 1
else:
if flowerbed[0]==0 and flowerbed[1]==0:
flowerbed[0]=1
count+=1
if flowerbed[-... |
def minion_game(string):
string=string.upper()
v=0
c=0
for i in range(len(string)):
if(string[i]in"AEIOU"):
v+=(len(string)-i)
else:
c+=(len(string)-i)
if(v>c):
print("Kevin",v)
elif(v<c):
print("Stuart",c)
else:
print("Draw")
... |
if __name__ == '__main__':
n = int(input())
l=[]
for _ in range(n):
abc=input().split()
a=abc[0]
if(a=='insert'):
b=int(abc[1])
c=int(abc[2])
l.insert(b,c)
elif(a=='print'):
print(l)
elif(a=='remove'):
b=int(... |
mobil = {
"brand" :
"Ford",
"tahun" : 2012
}
mobil["warna"] = "merah"
print(len(mobil))
print(mobil)
print(mobil["brand"]) |
from graphics import *
#opens up the text file
text_file = open("data.txt")
#reads the data text file
dataRead = text_file.read()
#splits up the data file and transfers it into a list
dataList = dataRead.split("\n")
#closes the file
text_file.close()
# Creates a window, 'ModuleData', to the size allocated
window =... |
mytuple= ('A','B','C','D','E')
print(mytuple[3])
print(mytuple[1:3])
print(mytuple[-3:-1])
Coming=('A','B','C')
Notcoming=('D','E','F')
Changes=list(Coming)
Changes.append('D')
Changes.append('E')
print(Changes)
Coming=tuple(Changes)
print(Coming)
Changes=list(Coming)
Changes.remove('C')
Changes.rem... |
# -*- coding: utf-8 -*-
"""Task solution:
https://www.codewars.com/kata/first-variation-on-caesar-cipher
"""
import math
RUNNERS = 5
NUMBERS_OF_LETTERS_IN_THE_ALPHABET = 26
def fib(num):
"""
Finds n-th element from a Fibonacci sequence.
:param num: int : sequence number.
:return: int : n-th elemen... |
print("""This is a puzzle favored by Einstein. You will be asked to enter
a three digit number, where the hundred's digit differs from the
one's digit by at least two. The procedure will always yield 1089
""")
ABC = input("Give me a number: ")
C = int(ABC) % 10
B = int((int(ABC) / 10) % 10)
A = int((int(ABC) / 10 ** 2... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Wiki.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import bs4 as bs
import urllib.request
import re
from nltk.corpus import stopwords
f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
make_trade_list.py
Creates a list of trades and writes them to disk
The file can be read by the risk_normalization program
Created on Tue Sep 15 19:06:42 2020
@author: howard bandy
"""
import matplotlib.pyplot as plt
import numpy as np
mean_gain = 0.001
std_dev_ga... |
from pydrummer.models.sound import Sound
class Mix(object):
"""A Mix is a single multi-sound pattern created by combing Sequences.
A Mix is used for rhythm playback.
TODO: Look into merging steps into one big wave file where notes can
continue to play until they finish instead of cutting every sound... |
import re
pattern = r"abc"
string = "abc"
match_object = re.match(pattern, string)
print(match_object) # <re.Match object; span=(0, 3), match='abc'> match - показывает вхождение шаблона внутрь строки.
# span - показывает с какой по какую позицию содержится вхождение шаблона в строку
string = "babcde" # None
... |
f = open("text.txt", "r")
# x = f.read() # чтение всего файла целиком
# x = f.read(10) # чтение первых 10 символов(?)
# print(repr(x)) # ''''First\nSecond\nThird', repr - это однозначное (недвусмысленное) представление объекта
# в виде строки, такой, чтобы возможно было бы из этого представления сделать такой же... |
"Задача: отсортировать имена по длине"
x = [("Guido", 'Van', "Rossum"), ("Haskell", "Curry"), ("John", "Backus")]
def length(name):
return len("".join(name)) # разрезаем имена по пробелу, склеиваем и выводим длину
x.sort(key=length) # сортируем по длине, используя функции key и length
print(x)
"Сокращаем ... |
import csv
with open("example.csv") as f:
reader = csv.reader(f)
for row in f:
print(row)
# Если в файле у значения дробная часть отделена от целой не точкой а запятой, мы можем выделить значение кавычками
# student,good,90,"90,2",100
# Также если элемент записан в две строки, мы можем выде... |
import torch
import torch.nn as nn
from torch.autograd import Function
class ReLU(Function):
def forward(ctx, x):
# 在forward中,需要定义MyReLU这个运算的forward计算过程
# 同时可以保存任何在后向传播中需要使用的变量值
ctx.save_for_backward(x) # 将输入保存起来,在backward时使用
output = input_.clamp(min=0) # rel... |
from abc import ABC, abstractmethod
class InventoryException( Exception):
status = ''
message = ''
def __init__(self, statusORcopy, message =None):
if message==None:
self.status = statusORcopy.status
self.message =statusORcopy.message
else:
s... |
#E: Un número
#S: Averiguar la sumatoria de un número
#R: Número debe ser entero positivo
def sumatoria(ini,fin):
if isinstance(ini,int) and isinstance(fin,int)and ini>=0 and fin>=0:
if fin==0:
return ini
else:
return ini+sumatoriaaux(ini,fin,0)
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 23:01:47 2020
@author: feng
"""
from mergesort import mergeSort
def Count_Inversions(arr):
while len(arr) > 2:
l = Count_Inversions(arr[:len(arr)//2])
r = Count_Inversions(arr[len(arr)//2:])
m = Count_Split(arr[:len(arr)//2],arr[len(arr)//2:... |
#!/usr/bin/python3
def main():
"""
docstring
Here's an explanation.
"""
# Comment out
# Care about indent
print("Hello, world!")
x = 'text'
print(x)
y = 100
print(y)
print(x,y)
print(x + ' ', end='')
print(y)
z = 'mojiretu'
print(x + z)
print(x... |
people = {1:{'name':'john','age':'28','sex':'male'},2:{'name':'Marie','age':'24','sex':'female'}}
for p_id,p_info in people.items():
print("\nperson ID:",p_id)
for key in p_info:
print(key + ':',p_info[key])
|
a = int(input("Enter a five digit number: "))
print(a)
rev=0
while(a!=0):
i=a%10;
rev=(rev*10)+i
a=a//10;
print(rev)
|
class Contact:
def __init__(self,name,number,email):
self.name=name
self.number=number
self.email=email
def __str__(self):
return (self.name,self.number,self.email)
def main():
my_contact=Contact('viral','6895412','viral@gmail.com')
print(my_contact.__str__()... |
# Dictionary
fruit = {
'orange': 'a sweet, ornage citrus fruit',
'apple': 'good for maing cider',
'lemon': 'a sour, yellow citrus fruit',
'grape': 'a small, sweet fruit growing in bushes'
}
# print(fruit)
# print(fruit['lemon'])
#
# fruit['pear'] = 'an odd shaped apple'
# print(fruit)
#
# fruit['... |
text = ("А роза упала на лапу Азора")
text = text.split(' ')
print("Enter your n. "
"Or print 0 if you don't want to continue")
n=1
while n!=0:
n = int(input())
if n not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]:
print("Change value")
else:
n = int(n)
n= int(n)
result = []
for word... |
import sqlite3
conn = sqlite3.connect('database.db')
print("database created")
c = conn.cursor()
def create(c):
sql_create = """
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id integer unique primary key autoincrement,
name text
);
"""
c.executescript(sql_crea... |
class SymbolTable:
def __init__(self):
self.symbol_table = []
self.symbol_table.append(dict())
self.scope = 0
def __str__(self):
return "{0}".format(self.symbol_table)
def add_object(self, key, new_obj):
self.symbol_table[self.scope]
self.symbol_tab... |
"""Spectrum Effect for BlyncLight
"""
from typing import List, Tuple
import math
def Spectrum(
steps: int = 64,
frequency: Tuple[float, float, float] = None,
phase: Tuple[int, int, int] = None,
center: int = 128,
width: int = 127,
) -> Tuple[float, float, float]:
"""Generator function that re... |
# https://www.hackerrank.com/challenges/the-power-sum/problem
def powerSum(X, N, candidate):
candidateRes = pow(candidate, N)
if candidateRes < X:
return powerSum(X, N, candidate+1) + powerSum(X - candidateRes, N, candidate+1)
if candidateRes==X:
return 1
return 0
if __name__ == '__mai... |
# https://projecteuler.net/problem=12
from math import sqrt
def countFactors(n):
count = 0
for x in range(1, int(sqrt(n))):
if n % x == 0:
count += 1
if x*x != n:
count += 1
return count
def largestTriangleNumber(minFactorCount):
t, lastInt, tCount = 1,... |
# https://projecteuler.net/problem=9
def pyth(sum):
for a in range(1,int(sum/(pow(2,0.5)+1))):
b = (0.5*pow(sum,2) - sum*a)/(sum - a)
if isInt(b):
c = sum - a - b
return a * b * c
raise Exception("Doesn't exist")
def isInt(n):
return n==int(n)
if __name__ == '__main... |
#problem: Given an unsorted integer array, find the smallest missing positive integer.
#shoudl run in O(n)
#questions:
#negatives?
#what happens if theyre all the same number
#no other data types?
#what shoul it return in a list of all negatives
#default return value
#assumptions:
def firstMissingPositive(nums):
... |
"""
Choose any website(s)
that you would like to scrape
and write a script to get the html
and save it to a file
(<filename>.html).
"""
import requests as r
wiki_korea_url = 'https://en.wikipedia.org/wiki/Korea'
headers = {'user-agent': 'Jeong Kim (tjtekrkchlrh@gmail.com)'}
response = r.get(wiki_korea_url, headers=... |
from raspi_lora import LoRa, ModemConfig
# This is our callback function that runs when a message is received
def on_recv(payload):
print("From:", payload.header_from)
print("Received:", payload.message)
print("RSSI: {}; SNR: {}".format(payload.rssi, payload.snr))
# Use chip select 0. GPIO pin 17 will be ... |
class Function_Calc:
def modular(self, value_1, value_2): # divisible function
if value_2 == 0:
return False
elif value_1 % value_2 == 0: # if the value_1 can be divided by the value_2 with no remainder, then return True
return True
else:
return False
... |
# Выводим на экран букву, которая находится в середине этой строки.
# Если эта центральная буква равна первой букве в строке, то создать
# и вывести часть строки между первым и последним символами исходной строки
str_line = input('Введите строку: ')
middle_str = int(len(str_line) / 2)
center_letter = str_line[middle_st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.